Merge two JS key value arrays

跟風遠走 提交于 2021-02-08 12:15:30

问题


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

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!