Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

JavaScript Array Push key value

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.

like image 682
daryl Avatar asked Oct 18 '11 20:10

daryl


People also ask

How do you push a key-value pair to an array?

Use map() to Push Key-Value Pair Into an Array in JavaScript We can only use this function if the function has only one statement. The map() method makes a new array by calling a function once for every array's element. It does not modify the original array and run for empty elements.

How do you push an object with a key in an array?

To push an object into an array, call the push() method, passing it the object as a parameter. For example, arr. push({name: 'Tom'}) pushes the object into the array. The push method adds one or more elements to the end of the array.

How do you push an array into an array?

The arr. push() method is used to push one or more values into the array. This method changes the length of the array by the number of elements added to the array. Parameters This method contains as many numbers of parameters as the number of elements to be inserted into the array.


2 Answers

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

like image 86
Felix Kling Avatar answered Oct 05 '22 21:10

Felix Kling


You may use:

  • Array.prototype.map()
  • Array.prototype.reduce()
  • Arrow functions
  • Comma operator

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);
like image 45
Mohammad Usman Avatar answered Oct 05 '22 22:10

Mohammad Usman