anthonyv
anthonyv

Reputation: 2465

IndexBy nested object value of type array

I am wanting to perform the below transformation, but am having trouble with how to do it, just wondering if anyone has any pointers:

//Source
[ 
   { types: ['a', 'b'] }, 
   { types: ['b'] }, 
   { types: ['a', 'c'] } 
]
//Transformation
{ 
   'a': [ { types: ['a', 'b'] }, { types: ['a', 'c'] }  ], 
   'b': [ { types: ['a', 'b'] }, { types: ['b'] } ],
   'c': [ { types: ['a', 'c'] } ]
}

Upvotes: 1

Views: 288

Answers (3)

Mahdi Pedram
Mahdi Pedram

Reputation: 749

    var data = [{
      types: ['a', 'b']
    }, {
      types: ['b']
    }, {
      types: ['a', 'c']
    }];

    var transform = function(records) {
    	var obj = {};
    	
    	records.forEach(function(record){
    		record.types.forEach(function(value){
                    obj[value] = obj[value] || []
    		    obj[value].push(record);
    		});
    	});
    
    	return obj;	
    };

    document.write('<pre>' + JSON.stringify(transform(data)) + '</pre>');

Upvotes: 0

Pranav C Balan
Pranav C Balan

Reputation: 115242

Use reduce() with forEach()

var data = [{
  types: ['a', 'b']
}, {
  types: ['b']
}, {
  types: ['a', 'c']
}];

var res = data.reduce(function(a, b) {
  b.types.forEach(function(v) { // iterate over inner array
    a[v] = a[v] || []; // define the property if not defined
    a[v].push(b); // push the object refence 
  });
  return a;
}, {});

document.write('<pre>' + JSON.stringify(res, 0, 3) + '</pre>');

For older browser check polyfill options of forEch and reduce methods.

Upvotes: 1

Jagdish Idhate
Jagdish Idhate

Reputation: 7742

We can use .reduce of Array & iterate

var test = [ 
   { types: ['a', 'b'] }, 
   { types: ['b'] }, 
   { types: ['a', 'c'] } 
]

test.reduce(function(res,obj,index){
   obj.types.forEach(function(x){
     res[x] = res[x] || [];
     res[x].push(obj)
    });
  return res;
},{});

Upvotes: 0

Related Questions