Search code examples
javascriptobjectjavascript-objectskey-value

Set dynamic key and values inside for loop


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 ?


Solution

  • 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.