30

Ok, I'm going a little wrong here and I've already wasted an hour with this so hopefully one of you guys can help me.

var a = ['left','top'],
    x = [];

for(i=0;i<a.length;i++) {
    x.push({
        a[i] : 0
    });
}

How do I go about pushing a value to each of the keys inside the var a array?

You can see my failed attempted but hopefully that will give you an insight into what I'm trying to achieve.

Anurag Uniyal
  • 85,954
  • 40
  • 175
  • 219
daryl
  • 14,307
  • 21
  • 67
  • 92

2 Answers2

55

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

Felix Kling
  • 795,719
  • 175
  • 1,089
  • 1,143
8

You may use:


To create array of objects:

var source = ['left', 'top'];
const result = source.map(arrValue => ({[arrValue]: 0}));

Demo:

var source = ['left', 'top'];

const result = source.map(value => ({[value]: 0}));

console.log(result);

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:

var source = ['left', 'top'];

const result = source.reduce((obj, arrValue) => (obj[arrValue] = 0, obj), {});

console.log(result);
Mohammad Usman
  • 37,952
  • 20
  • 92
  • 95