Reputation: 3
How do you take an array and turn it in to this using lo-dash
Takes an array
["BBC", "url", false, "Apple", "url", false, "Google", "url", false]
outputs:
[
{
"title" : "BBC",
"href" : "url",
"window_check": false
},
{
"title" : "Apple",
"href" : "url",
"window_check": false},
{
"title" : "Google",
"href" : "url",
"window_check": false
},
];
Currently I was doing this but failed.
var array123 = ["BBC", "url", false, "Apple", "url", false, "Google", "url", false];
_.reduce(array123, function(result, value, key) { result[key]=value; return result;}, {});
I got this.
{0: "BBC", 1: "url", 2: false, 3: "Apple", 4: "url", 5: false, 6: "Google", 7: "url", 8: false}
Upvotes: 0
Views: 89
Reputation: 4812
there ya go
var keys = ['title','href','window_check'];
var out = _.reduce(array123, function(result, value, idx) {
if (idx % keys.length == 0)
result.push({});
result[result.length - 1][keys[idx % keys.length]] = value;
return result;
},[]);
if you want to create new objects for every X items with objects, your logic actually needs to include that.
Upvotes: 1
Reputation: 664434
I wouldn't use underscore/lodash at all:
var result = [];
for (var i=0; i<array123.length; )
result.push({
"title": array123[i++],
"href": array123[i++],
"window_check": array123[i++]
});
If you want to take a functional approach, define some chunkN
method and then use
var result = _.chain(array123).chunkN(3).map(function(chunk) {
return {
"title": chunk[0],
"href": chunk[1],
"window_check": chunk[2]
}
}).value();
Upvotes: 2