合并2个具有不同值类型的数组 [英] Merging 2 arrays with different value types

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

问题描述

在MEAN堆栈中进行开发. Express接收并处理req数组参数(最初是字符串),Mongoose返回对象数组属性.我面临一个非常奇怪的问题. Console.log输出数组,如下所示:

Developing in MEAN stack. Express received and process req array parameters (initially string) and Mongoose returns object array property. I am facing very strange problem. Console.log outputs arrays as follows:

var arr1 = [ '5acde7adf7d2520e3b205970', '5acde7c0f7d2520e3b205971' ];
var arr2 = ["5acde7adf7d2520e3b205970","5acde7c0f7d2520e3b205971"];

第一个数组是一个JSON.parsed变量,第二个是MangoDB的属性返回的数组属性.

first array is a JSON.parsed variable, second the property of MangoDB returned array property.

我需要比较数组,如果它们不同,请执行操作.

I need to compare arrays and if they different - perform operation.

Lodash的isEqual函数始终为false. Lodash联合与concat和filter相同,输出数组如下(日志输出):

Lodash isEqual function is always false. Lodash union the same as concat and filter, output arrays as follows (log output):

[ 5acde7adf7d2520e3b205970,
  5acde7c0f7d2520e3b205971,
  '5acde7adf7d2520e3b205970',
  '5acde7c0f7d2520e3b205971' ]

如果我检查每个数组值的类型,则第一个数组值是对象,第二个数组是字符串...

If I check types of each array value then the first array values are objects the second are strings...

我可以属性合并数组的唯一方法是通过对数组进行预处理,例如:JSON.parse(JSON.stringify(arr1)).然后,所有值都是字符串,并按以下说明正确合并:

The only way I can property merge arrays is by preprocessing them like: JSON.parse(JSON.stringify(arr1)). Then all values are strings and merged properly as they shall:

[ '5acde7adf7d2520e3b205970', '5acde7c0f7d2520e3b205971' ]

有人遇到这个问题吗?可能对如何处理有更好的想法

Anybody faced this problem? Probably have some better ideas how to handle it

对于我的问题,我发现的最佳解决方案是使用map函数甚至对数组值进行排序.例如:

The best solution I found, for my problem, is to use map function to even array values. Ex:

arr2.map(String)

推荐答案

如果它总是原始数组,那么像这样比较它们的每个值应该很容易:

If it's always going to be an array of primitives, it should be quite easy to just compare each of their values like so:

const arr1 = [ '5acde7adf7d2520e3b205970', '5acde7c0f7d2520e3b205971' ];
const arr2 = ["5acde7adf7d2520e3b205970","5acde7c0f7d2520e3b205971"];
const isSame = (arr1, arr2) => {
  if (arr1.length !== arr2.length) return false;
  return arr1.every((arr1elm, i) => arr1elm === arr2[i]);
}
console.log(isSame(arr1, arr2));

一个数组可能已定义为双引号,而一个数组则已被反序列化的事实,因为它们已经被反序列化了-它仍然是下面的字符串数组,而不是字符串本身.

The fact that one array may have been defined with double quotes and one with single quotes shouldn't affect anything, since they're already deserialized - it's still an array of strings underneath, not a string itself.

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

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