Reputation: 189
I have two arrays, one a 'groups' array, and the other, an object 'items' array. I want to transform the data with these conditions:
You may only use underscore.js if it may help. Thanks!
var groups = ["group1", "group2"] // Can increase dynamically, e.g. ["group1", "group2", "group3"],
var items = // Given that the 'group' attribute of each item should correspond dynamically too with groups array increase/ decrease
[ // It can become ["group1", "group2", "group3"] as values in an item when the 'groups' array is ["group1", "group2", "group3"]
{
name: "object 1",
group: ["group1"]
},
{
name: "object 2",
group: ["group1", "group2"]
},
{
name: "object 3",
group: ["group2"]
}
]
It should transform to this:
var result =
[
{
name: "object 1",
group: ["true", "false"] // group attribute order should base on the groups array and increase in size as groups increase
}, // true in the first value since it has "group1" in the 'group' array attribute in the 'items' array and false as the second value because it doesn't have "group2"
{
name: "object 2",
group: ["true", "true"]
},
{
name: "object 3",
group: ["false", "true"]
}
]
And BTW, this will be used for displaying data in a table in an angular JS app. Where the column headers are the 'groups' array and the rows are the 'result' array.
Upvotes: 0
Views: 54
Reputation: 999
var groups = ["group1", "group2"] // Can increase dynamically, e.g. ["group1", "group2", "group3"],
var items = // Given that the 'group' attribute of each item should correspond dynamically too with groups array increase/ decrease
[ // It can become ["group1", "group2", "group3"] as values in an item when the 'groups' array is ["group1", "group2", "group3"]
{
name: "object 1",
group: ["group1"]
},
{
name: "object 2",
group: ["group1", "group2"]
},
{
name: "object 3",
group: ["group2"]
}
];
function transform(items, groups) {
return _.map(items, function(item) {
var groupsTransformed = _.map(groups, function(group) {
return (item.group.indexOf(group) >= 0);
});
item.group = groupsTransformed;
return item;
});
}
var transformedData = transform(items, groups);
document.getElementById('res').innerHTML = JSON.stringify(transformedData);
console.log(transformedData);
Upvotes: 0