Zenon
Zenon

Reputation: 91

Javascript array built dynamically in a loop

I have an array, say

var arr = ["id", "currency", "region", "status"]

How can I map the above to an object literal, as below?

var columns = [
      { key:"id",        headerRenderer:"id" },
      { key:"currency",  headerRenderer:"currency" },
      { key:"status",    headerRenderer:"region" },
      { key:"region",    headerRenderer:"status" }
    ];

Thanks in advance!

Upvotes: 0

Views: 67

Answers (4)

Christian Zosel
Christian Zosel

Reputation: 1424

The map method on the Array prototype allows you to apply a function to every element in an array, thereby effectively abstracting iteration for simple cases. Your case is simple, because the content of any entry in result is completely specified by its corresponding entry in arr, which means you can "map"

"id" --> { key: "id", headerRenderer: "id" }

Using map you can solve your problem in just one line (provided your environment supports ES6):

var arr = ["id", "currency", "region", "status"]

var result = arr.map(key => ({ key, headerRenderer: key }));

console.log(result);

Upvotes: 3

Redu
Redu

Reputation: 26161

Normally .map() is the way but another functional approach would be to use a tail call recursive map as follows;

var arr = ["id", "currency", "region", "status"],
   mapo = (a, r=[]) => a.length ? mapo(a.slice(1),r.concat({key:a[0],headerRenderer:a[0]})) : r;
console.log(mapo(arr));

Upvotes: 1

Mihai Alexandru-Ionut
Mihai Alexandru-Ionut

Reputation: 48357

One solution is to use Array#map method.

The map() method creates a new array with the results of calling a provided function on every element in this array.The provided function is a callback.

So, as I said above map method provided callback function once for each element in an array, in order, and constructs a new array from the results. The elements from the result array are objects, like this: {"key":item, "headerRenderer":item}.

var array = ["id", "currency", "region", "status"]
var columns=array.map(function(item){
    return {
      "key":item,
      "headerRenderer":item
    }
});
console.log(columns);

Upvotes: 4

bini
bini

Reputation: 154

var columns = [];
var array = ["id", "currency", "region", "status"];

for (var i = 0, len = array.length; i < len; i++) {
  columns.push({
    key: array[i],
    headerRenderer: array[i]
  });
}

Upvotes: 2

Related Questions