-2

I have two arrays're contained objects and i need to put elements(objects) to first array How to do that ? mybe with underscore?


Decastrio
  • 133
  • 1
  • 10

3 Answers3

3

Plain JS:

arr = [1,2,3,4]
arr1 = [6,7]
arr = arr.concat(arr1)

Using underscore

arr = [1,2,3,4]
arr1 = [6,7]

arr.push(arr1)
arr = _.flatten(arr)
Cyril Cherian
  • 30,992
  • 7
  • 41
  • 50
1

underscore / lodash is not required

var numbers = [1, 2, 3];
var letters = ['a', 'b', 'c'];
var numbers = numbers.concat(letters);

document.write(JSON.stringify(numbers));
Alexander Elgin
  • 5,926
  • 4
  • 33
  • 47
0

If you want to merge two array contaning objects, you have to choose field of object by which you want to merge.

array1 = [
 {field: 'username', display: 'username', hide: true},
 {field: 'age', display: 'Age', hide: true},
 {field: 'height', display: 'Height', hide: true}
]

array2 = [
{field: 'username', display: 'username 123', hide: false},
{field: 'age', hide: false}
]

Underscore -function-

_.values(_.extend(_.indexBy(array1, 'field'), _.indexBy(array2, 'field')))

We use indexBy to turn the arrays into objects keyed on the field value, and then extend does what we want. Finally, values turns it back into an array.

result -

 array3 = [
{field: 'username', display: 'username 123', hide: false},
{field: 'age', display: 'Age', hide: false},
{field: 'height', display: 'Height', hide: true}
]