How to convert these following inputs into output.
Input:
[{"id":1, "subid":5},
{"id":1, "subid":9},
{"id":2, "subid":16},
{"id":2, "subid":27}]
Output:
[{1:[5,9]},
{2:[16,27]}]
This is what I have tried so far:
var newobj = new Object();
listOfObject.forEach(function(i) {
var id = i.id
newobj[id] = []
newobj[id].push(i.subid)
return newobj
})
Reduce the data like this:
var arrayData = [{"id":1, "subid":5}, {"id":1, "subid":9}, {"id":2, "subid":16}, {"id":2, "subid":27}];
var result = arrayData.reduce(function (result, obj) {
var id = obj.id;
result[id] = (result[id] || []);
result[id].push(obj.subid);
return result;
}, {});
Underscore utilities are quite handy for array and object manipulations. Try this:
var list = [{"id":1, "subid":5}, {"id":1,"subid":9},{"id":2,"subid":16}{"id":2, "subid":27}]
_.mapObject(_.groupBy(list, 'id'), function(val){
return val.map(function(obj){
return obj.subid
})
})
var input = [
{"id":1, "subid":5},
{"id":1, "subid":9},
{"id":2, "subid":16},
{"id":2, "subid":27}
];
var output = [];
for (var i = 0; i < input.length; i++) {
var id = input[i].id;
var subid = input[i].subid;
if (output[id] == null) {
output[id] = [];
}
output[id].push(subid);
}
I'd just iterate through the input array and check for the existence of an existing property, then add a new object or push to the existing array.
var input = [ {"id":1, "subid":5}, {"id":1, "subid":9}, {"id":2, "subid":16}, {"id":2, "subid":27} ]; var output = []; input.forEach(function(a){ var existing = output.find(function(b){ return b.hasOwnProperty(a.id); }); existing ? existing[a.id].push(a.subid) : output.push({[a.id]: [a.subid]}); }); console.log(output);
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.