JavaScript Array Push key value
You have to use bracket notation:
var obj = {};obj[a[i]] = 0;x.push(obj);
The result will be:
x = [{left: 0}, {top: 0}];
Maybe instead of an array of objects, you just want one object with two properties:
var x = {};
and
x[a[i]] = 0;
This will result in x = {left: 0, top: 0}
.
You may use:
To create array of objects:
var source = ['left', 'top'];const result = source.map(arrValue => ({[arrValue]: 0}));
Demo:
Or if you wants to create a single object from values of arrays:
var source = ['left', 'top'];const result = source.reduce((obj, arrValue) => (obj[arrValue] = 0, obj), {});
Demo: