1

Is it possible to add a variable name of each objects inside in an array in JavaScript. I mean something like this (pseudocode):

var arr = [ 
    object 1 name { 
        key1: "some value",
        key2: "some value",
        key3: "some value"
    }, 
    object 2 name { 
        key1: "some value",
        key2: "some value",
        key3: "some value"
    }
]

or it's only possible to be like this :

var arr = [ 
    { 
        key1: "some value",
        key2: "some value",
        key3: "some value" 
    },
    { 
        key1: "some value",
        key2: "some value",
        key3: "some value"
    }
]

What I'm trying to say is, can I give a name for each object element inside an array?

Thank you in advance.

2 Answers 2

1

If you find yourself wishing to name members of an array (presumably for lookup by name later), you should probably use a dictionary (ie. an object) instead.

var data = { 
    object1: {
        key1: "some value",
        key2: "some value",
        key3: "some value"
    },
    object2: { 
        key1: "some value",
        key2: "some value",
        key3: "some value"
    }
};

Then, you can access object2 like this:

var object2 = data.object2; or var object2 = data['object2'];

On the other hand, you can access members of an array by their index like this:

var object2 = arr[1];

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

1 Comment

this is the best way to go - also note: Object.values(data) returns an array holding all the values of your dictionary
0

If you still want to have an array, you can do so by naming each item in that array (your choice if you want the sub-data at the same level, or nested).

var data = [
  {
    id: "John",
    data: {
      key1: "some value",
      key2: "some value",
      key3: "some value"
    }
  },
  {
    id: "Susan",
    data: { 
      key1: "some value",
      key2: "some value",
      key3: "some value"
    }
  }
];

Comments

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.