简体   繁体   中英

How to concat javascript array in an object

could someone help me concat an array to another array that is part of a javascript object? So far I have tried:

var someObj = {};
someObj.someArray = ['1', '2', '3', '4'];

var randomArray = ['5', '6', '7']


someObj.someArray.concat(randomArray);

console.log(someObj);

However, the final object contains the original array, not the original array concated with the randomArray .

Here's my fiddle:

http://jsfiddle.net/d8md3r7a/

Take a look at the MDN documentation for Array.prototype.concat :

The concat() method is used to merge two or more arrays. This method does not change the existing arrays, but instead returns a new array . (Emphasis mine)

As you can see, the method does not actually change the array in place. The new array is returned from the method, so you'll need to assign the to the returned array like so:

someObj.someArray = someObj.someArray.concat(randomArray);

Array.concat() doesn't modify the original array but returns the concatenated results. You need to use the return value of Array.concat() to explicitly set the original object property. Updated your fiddle here .

You can do something like this instead of .concat() .

 var someObj = {}; someObj.someArray = ['1', '2', '3', '4']; var randomArray = ['5', '6', '7'] randomArray.forEach(v => someObj.someArray.push(v)); console.log(someObj); 

concat makes a new array and is used like this

someObj.someArray = someObj.someArray.concat(randomArray);  

Another way is to modify the array in place by inserting the additional elements. To do that, use push together with Function.apply like this:

[].push.apply(someObj.someArray, randomArray);  

Function.apply takes two parameters, the first is a this value and the second is an array that is used to fill in the function parameters. Here, Function.apply causes the elements of randomArray to be unwrapped from the array as (multiple) parameters to the push function, instead of pushing the entire array as a single element. The [] is a trick to create a blank array to grab the push function, instead of the more verbose someObj.someArray.push or Array.prototype.push .

To echo the answer above. The use of the .concat() method is definitely the way to go. You could also use the ES6 spread operator which can be used like push and concat. This will give you the results you are looking for.

var someObj = {};
someObj.someArray = ['1', '2', '3', '4'];

var randomArray = ['5', '6', '7']


someObj.someArray.push(...randomArray);

console.log(someObj);

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM