1

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'] } ]
}

3 Answers 3

1

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.

Sign up to request clarification or add additional context in comments.

1 Comment

Cool!! we are on same page +1
0

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;
},{});

Comments

0

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

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.