1

I have JSON array like this:

var items = [
   [{id:1,name:'test'},{id:2,name:'test'},...]  ,
   [{id:1,name:'test'},{id:2,name:'test'},...]  ,
]

From that I need an array like this:

var newArray = [
  { id: 1, name: 'test' }, { id: 2, name: 'test'}, { id: 3, name: 'test'}, ...
]

Now I am using a for loop on items array and storing into newArray but is there any other method without using loops?

Balázs
  • 2,929
  • 2
  • 19
  • 34
Jabaa
  • 1,743
  • 7
  • 31
  • 60

2 Answers2

1

Demo 1: concat() and .apply()


Demo 2: reduce() and concat()
Demo 3: ... Spread Operator and concat()

Demo 1

var items = [
   [{id:1,name:'test'},{id:2,name:'test'}]  ,
   [{id:1,name:'test'},{id:2,name:'test'}]  ,
]

var flattened = [].concat.apply([], items);

console.log(flattened);

Demo 2

var items = [
   [{id:1,name:'test'},{id:2,name:'test'}],
   [{id:1,name:'test'},{id:2,name:'test'}]
];

var flattened = items.reduce(function(prev, curr) {
  return prev.concat(curr);
});

console.log(flattened);

Demo 3

var items = [
   [{id:1,name:'test'},{id:2,name:'test'}],
   [{id:1,name:'test'},{id:2,name:'test'}] 
];

var flattened = [].concat(...items);

console.log(flattened);
zer00ne
  • 41,936
  • 6
  • 41
  • 68
1

I love functional and new prototpes of array so here is my demo

var items = [
   [{id:1,name:'test'},{id:2,name:'test'}]  ,
   [{id:1,name:'test'},{id:2,name:'test'}] 
]
var ll = items.reduce(function(prev, current){return prev.concat(current)})
console.log(ll)
Álvaro Touzón
  • 1,247
  • 1
  • 8
  • 21