0

var menu = [];
$('.mainmenu').click(function() {
  $('.mainmenu').each(function(i,v) {

    var sub = {};
    var indexmenu = $(this).attr('id');
    sub[indexmenu] = $(this).attr('data-currstate');
    menu.push(sub);

  })
  $.each(menu,function(i,v) {
    console.log(i)
    console.log(v)
  })
})
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<a target="_top" href="#" class='mainmenu' id='maintenance' data-currstate='hide'>
  <i class="fa fa-cogs"></i> Maintenance
</a>

I want to create an array of object from a menu wherein I want the ID of each menu to be the index and the value will be state.

  1. I want the id of each menu to be the index and the state to be the value
  2. What i get is the id and value becomes the value

Note:

In my actual code the creation of the menu array happens on load of page in demo I created it on click. Also the reason why I created on load is that I store the value in local storage. I made the demo as simple as I can

6
  • 1
    Can you please add an example of expected output? Commented Dec 14, 2018 at 5:46
  • @Justcode in the console log I want to get maintenance as index instead of 0and hide as value instead of {"maintenance":"value"} Commented Dec 14, 2018 at 5:48
  • You mean this { "0": "hide" }? Commented Dec 14, 2018 at 5:51
  • 1
    I believe @guradio want 0 (i) as maintenance Commented Dec 14, 2018 at 5:52
  • Mukyuu is correct I want 0 to be maintenance Commented Dec 14, 2018 at 5:57

1 Answer 1

1

You can use Map instead of object.

This is a part of ES6, so you will have browser compatibility issues. You can check compatibility.

ES6 introduced 2 new classes: Map and Set, which are similar to Array and Objects, but with 1 major difference. Their keys can be anything. So you can have array index as non-numeric values as well. If you want them to be unique, you can look into Set.

var menu = new Map();
$('.mainmenu').click(function() {
  $('.mainmenu').each(function(i,v) {
    menu.set($(this).attr('id'), $(this).attr('data-currstate'));
  })
  for( const [k, v] of menu.entries()) {
    console.log(`Key: ${k} | Value: ${v}`)
  }
})
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<a target="_top" href="#" class='mainmenu' id='maintenance' data-currstate='hide'>
  <i class="fa fa-cogs"></i> Maintenance
</a>

Sign up to request clarification or add additional context in comments.

3 Comments

this is what I wanted can you add a bit more explanation please
happy coding mate
@guradio Please check the update. Hope it answers your queries

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.