Misha91191
Misha91191

Reputation: 11

How to add to the javascript object to the same value

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

Upvotes: 0

Views: 692

Answers (1)

Vitim.us
Vitim.us

Reputation: 22138

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',
      ...
   },
}

Upvotes: 2

Related Questions