1

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 
})
0

4 Answers 4

5

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;
}, {});
Sign up to request clarification or add additional context in comments.

Comments

3

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
       })       
 })

2 Comments

Love it. More than my own answer. I'll switch to underscore utilities :)
@vivekmaharajh Also check out lodash.
0
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);
}

Comments

0

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);

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.