Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Set dynamic key and values inside for loop [duplicate]

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 ?

like image 345
Aditya Avatar asked Sep 23 '26 00:09

Aditya


2 Answers

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.

like image 151
Nisarg Shah Avatar answered Sep 24 '26 14:09

Nisarg Shah


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);
like image 34
amrender singh Avatar answered Sep 24 '26 14:09

amrender singh



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!