3

It seems like a basic thing but i am unable to find where i am going wrong .

I want output in this key value format .

[{"10":"bob"},{"20":"Tom"},{"30":"Larry"}]

What i am doing -

var list = [];
var names = ["Bob","Tom","Larry"];
var ages =  ["10", "20", "30"];
for(var i=0; i<names.length; i++){
    list.push({ages[i] : names[i]})
}

But i am getting unexpected token error . Kindly guide where i am going wrong ?

2
  • 2
    You need to enclose the key in [] to impose Computed property names. Commented Aug 3, 2018 at 7:04
  • Why do you want that datastructure? It makes little sense. Commented Aug 3, 2018 at 7:07

2 Answers 2

8

To set a dynamic string as a property of an object, you can use square bracket notation (obj[propVariable]). So, just store an empty object into a variable (var item = {}), and then you can set its property through item[propVariable].

var list = [];
var names = ["Bob","Tom","Larry"];
var ages =  ["10", "20", "30"];
for(var i=0; i<names.length; i++){
  var item = {};
  item[ages[i]] = names[i];
  list.push(item);
}
console.log(list);

You can read more about square bracket notation here and here.

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

Comments

6

To create dynamic properties you need to use bracket notation : Try the following:

var list = [];
var names = ["Bob","Tom","Larry"];
var ages =  ["10", "20", "30"];
for(var i=0; i<names.length; i++){
    list.push({[ages[i]] : names[i]})
}
console.log(list);

1 Comment

why downvotes for this answer? it actually works fine.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.