【发布时间】:2021-11-05 21:22:47
【问题描述】:
我对此进行了很多搜索,但没有找到任何可以启发我了解我的问题的内容:
我有这个代码:
let array1 = ["a", "b", 3, {
p1: 'hola'
}, "c", "d"],
array2 = [1, 2, {
p1: 'adios'
}],
result = [],
i, l = Math.min(array1.length, array2.length);
for (i = 0; i < l; i++) {
if (typeof array1[i] === 'object' && typeof array2[i] === 'object') {
result.push(array2[i], ...(JSON.stringify() === JSON.stringify() ?
[] :
[array1[i]]
));
} else {
result.push(array2[i], array1[i]);
}
}
result.push(...array1.slice(l), ...array2.slice(l));
console.log(result);
我已经根据建议修改了代码,现在代码是这样做的:
我们有两个数组;
array1 = ["a", "b", 3, {p1: 'hello'},"c", "d"] array2 = [1, 2, {p1: 'hello'}]
现在的结果是基于代码的:
结果:[1, 'a', 2, 'b', {p1: 'hello'}, 3, {p1: 'hello'}, 'c', 'd']
这很好,因为我不想省略两个数组之间索引不同的对象,现在的问题是当两个数组中的对象在同一索引中时,这段代码;
array1 = ["a", "b", {p2: '再见'},"c", "d"] array2 = [1, 2, {p1: 'hello'}]
结果:[1, 'a', 2, 'b', {p1: 'hello'}, 'c', 'd']
这是我现在的问题,我想要的是当两个数组的相同索引中有对象时比较对象的属性并且相同跳过第一个数组对象并将第二个传递给最终数组,但是如果属性不一样,把对象的属性合二为一,这是我想要的理想结果:
array1 = ["a", "b", {p2: '再见'},"c", "d"] array2 = [1, 2, {p1: 'hello'}]
结果:[1, 'a', 2, 'b', {p1: 'hello', p2: 'goodbye'}, 'c', 'd']
【问题讨论】:
-
你不能只在
for中添加一个if语句来检查两者是否相同,如果相同,只推其中一个而不是两个?跨度>
标签: javascript arrays object