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 ?

Aditya
  • 431
  • 1
  • 7
  • 21
  • 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

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.

Nisarg Shah
  • 14,151
  • 6
  • 34
  • 55
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,949
  • 3
  • 22
  • 28