2

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 ?

Aditya
  • 421
  • 1
  • 7
  • 20
  • 2
    You need to enclose the key in `[]` to impose [Computed property names](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/Object_initializer#Computed_property_names). – 31piy Aug 03 '18 at 07:04
  • Why do you want that datastructure? It makes little sense. – Jonas Wilms Aug 03 '18 at 07:07

2 Answers2

7

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.

Nisarg Shah
  • 13,626
  • 5
  • 36
  • 53
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);
amrender singh
  • 7,430
  • 3
  • 20
  • 27