I need to merge two JS arrays, but using concat fn or lodash library i can't do it...
I have two arrays like these:
[ test2: 'string', test: 'string' ]
[ nome: 'string',test2: 'string', test: 'string' ]
And what i need is to have result array like this:
[ test2: 'string', test: 'string', nome: 'string' ]
How can i do this? i tried several methods withouth success...
Array concat doesn't work...
Thanks
var obj1 = { 'test2': 'string', 'test': 'string' }; var obj2 = { 'nome': 'string','test2': 'string', 'test': 'string' }; const object3 = {...obj1, ...obj2 } console.log(object3)
If both objects have a property with the same name, then the second object property overwrites the first.
You're using arrays as a key:value pair, but in Javascript that data type is an object. Your two inputs turned into objects look like this:
{ test2: 'string', test: 'string' }
{ nome: 'string', test2: 'string', test: 'string' }
To merge these two objects you can use the ECMAScript 2018 Object Spread syntax.
const obj1 = { test2: 'string', test: 'string' };
const obj2 = { nome: 'string',test2: 'string', test: 'string' };
const newObj = {...ob1, ...ob2}
Note that because your objects share the same name and value pairs, there is only one copy of test:'string'
and test2:'string'
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.