问题
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
回答1:
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.
回答2:
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'
来源:https://stackoverflow.com/questions/57204189/merge-two-js-key-value-arrays