合并两个JS键值数组 [英] Merge two JS key value arrays

查看:151
本文介绍了合并两个JS键值数组的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我需要合并两个JS数组,但是使用concat fn或lodash库我无法做到...

I need to merge two JS arrays, but using concat fn or lodash library i can't do it...

我有两个这样的数组:

[ 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...

数组concat无效...

Array concat doesn't work...

谢谢

推荐答案

您将数组用作key:value对,但是在Javascript中,数据类型是对象.您的两个输入变成了对象,如下所示:

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' }

要合并这两个对象,可以使用ECMAScript 2018

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}

请注意,因为您的对象共享相同的名称和值对,所以只有 test:'string' test2:'string'

Note that because your objects share the same name and value pairs, there is only one copy of test:'string' and test2:'string'

这篇关于合并两个JS键值数组的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆