I have a some json data that I want to transform into an array of objects that should have the following structure:
var names =[{
name:"2Anita",
years:[1916,1917],
born:[11,20]
},
{
name:"2Anna",
years:[1916,1917],
born:[153,91]
}]
The source data has this structure:
{
"people": [{
"key": ["2Anita", "1916"],
"values": ["11"]
}, {
"key": ["2Anita", "1917"],
"values": ["20"]
}, {
"key": ["2Anna", "1916"],
"values": ["153"]
}, {
"key": ["2Anna", "1917"],
"values": ["91"]
}]
}
This is what I have achieved so far:
var people = [{
"key": ["2Anita", "1916"],
"values": ["11"]
}, {
"key": ["2Anita", "1917"],
"values": ["20"]
}, {
"key": ["2Ann", "1920"],
"values": [".."]
}, {
"key": ["2Anna", "1916"],
"values": ["153"]
}, {
"key": ["2Anna", "1917"],
"values": ["91"]
}, {
"key": ["2Ann-Christin", "1916"],
"values": [".."]
}, {
"key": ["2Ann-Christin", "1917"],
"values": [".."]
}]
var tempNames = [];
var names = [];
//Creating array that holds every unique name
people.forEach(function functionName(v, k) {
if (tempNames.indexOf(v.key[0]) === -1) {
tempNames.push(v.key[0])
}
});
//Creating array with objects for each unique name
tempNames.forEach(function(v, k) {
names.push({
name: v,
years: [],
born: []
})
});
JS Bin:
https://jsbin.com/qofuqatoqo/1/edit?html,js,console
EDIT:
My final solution:
var grouped = _.groupBy(people, function(num) {
return num.key[0];
});
var j = 0;
var n = _.each(grouped, function(val) {
vm.names.push({
name: val[0].key[0],
years: [],
born: []
})
for (var i = 0; i < val.length; i++) {
vm.names[j].years.push(val[i].key[1]);
vm.names[j].born.push(val[i].values[0]);
vm.years.push(val[i].key[1]);
}
j++;
});