0

Let's say I have var name = {} and on my html page I have elements with the classes, once you click on one element it opens more elements and I want to store those IDs. However, I want to store it as a nested array. For example, click on the element(I select the class) and then opens more elements and I select different elements(I record each ID)

name[class]=[idOfTheElement];

So the question is how can I have a hierarchy like name[class]= and then more than one idOfTheElement

1
  • 1
    Welcome to stackoverflow! Can you share a pice of code of what you're trying to accomplish? that way it will be easier to give you a more appropriate answer Commented Sep 14, 2019 at 15:36

1 Answer 1

2

You can just add an object inside another object or array. This will depend on what kind of structure you want

Array

var name = {};
name[class]=[]; //<- for each new class you create an empty array that you can add elements to it later
name[class][0] = 'id1'; // like this
name[class][1] = 'id2';

name[class].push('id3'); // this is another way of adding elements to an array

// You will end up with a structure that looks like this
{
   className1: ['id1', 'id2' ...],
   className2: ['id3', 'id4' ...]
}

Object

var name = {}; //<- for each new class you create an empty object that you can add properties to it later
name[class]={};

// adding properties
name[class]['id1'] = 'something';
name[class]['id2'] = 'something';

// You will end up with a structure that looks like this
{
   className1: {
     'id1': 'something',
      id2': 'something'
      ...
   },
    className2: {
     'id3': 'something',
      ...
   },
}
Sign up to request clarification or add additional context in comments.

3 Comments

name[class][0] = 'id', so do I put [0] inside of the loop and increment each time?
It depends, if you just want to only store the id you can put all of them inside an array. or if you want to store something related for each id, you can use a object which works like a map between two things.
@Misha91191the 0 is an index you can use a variable inside a for loop. like name[class][i] or you can just use a method called push it automatically adds elements to the end of the array, so it would be name[class].push(id)

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.