abhinav singh abhinav singh - 1 month ago 7
Javascript Question

Flatten a nested array of objects over a array field

Have an object a1 =

[{name:'x',age:21, addr:[{flat:1,add:'xyz'},{flat:2,add:'xsr'}]},
{name:'y',age:22, addr:[{flat:3,add:'xyz1'},{flat:4,add:'xsr1'}]]


Desired output:

[{name:'x',age:21, addr:{flat:1,add:'xyz'}},
{name:'x',age:21, addr:{flat:2,add:'xsr'}},
{name:'y',age:22, addr:{flat:3,add:'xyz1'},
{name:'y',age:22, addr:{flat:4,add:'xsr1'}]


Please suggest! I am trying to accomplish this using lodash/underscore.

Answer

Map every item in the original array to a new array, with a number of items according to the number of addr fields. Using concat flatten everything to a new array.

You can create new items using Object.assign() if you're transpiling to ES5 with babel or similar, as it's not supported by IE. However, since you're using angular, you can use angular.extend instead.

ES5:

var arr = [
  {name:'x',age:21, addr:[{flat:1,add:'xyz'},{flat:2,add:'xsr'}]},
  {name:'y',age:22, addr:[{flat:3,add:'xyz1'},{flat:4,add:'xsr1'}]}
];
   
var result = [].concat.apply([], arr.map(function(item) {     
  return item.addr.map(function(addr) {
    return angular.extend({}, item, { addr: addr });
  });
}));

console.log(result);
<script src="https://cdnjs.cloudflare.com/ajax/libs/angular.js/1.5.8/angular.min.js"></script>

ES6:

const arr = [
  {name:'x',age:21, addr:[{flat:1,add:'xyz'},{flat:2,add:'xsr'}]},
  {name:'y',age:22, addr:[{flat:3,add:'xyz1'},{flat:4,add:'xsr1'}]}
];
   
const result = [].concat(...arr.map((item) => item.addr.map((addr) => Object.assign({}, item, { addr }))));

console.log(result);