abhinav singh abhinav singh - 1 year ago 84
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 Source

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.


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

<script src="https://cdnjs.cloudflare.com/ajax/libs/angular.js/1.5.8/angular.min.js"></script>


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


Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download