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,919
  • 2
  • 16
  • 34
Jabaa
  • 1,643
  • 5
  • 28
  • 57

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
  • 36,692
  • 5
  • 39
  • 58
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,237
  • 1
  • 8
  • 21