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!
4 Answers 4
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);
Comments
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);
Comments
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]
});
}
Comments
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));
var 1is a syntax error.