【问题标题】:Merge objects from two arrays of object based in the index根据索引合并两个对象数组中的对象
【发布时间】: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


【解决方案1】:

我想这就是你所追求的。

let array1 = ['a', 'b', { p2: 'goodbye' }, 'c', 'd'];
let array2 = [1, 2, { p1: 'hello' }];

let result = [];
for (let i = 0; i < Math.max(array1.length, array2.length); i++) {
  if (typeof array1[i] == 'object' && typeof array2[i] == 'object') {
    result.push({ ...array2[i], ...array1[i] });
  } else {
    array2[i] && result.push(array2[i]);
    array1[i] && result.push(array1[i]);
  }
}

console.log(result);

【讨论】:

  • 非常感谢您解决我的问题!
【解决方案2】:

您可以比较这些项目,如果相同则省略第二个项目。

let array1 = ["a", "b", {p1: 'hello world'},"c", "d"],
    array2 = [1, 2,  {p1: 'hello world'}],
    result = [],
    i, l = Math.min(array1.length, array2.length);
    
for (i = 0; i < l; i++) {
    result.push(array2[i], ...(JSON.stringify() === JSON.stringify()
        ? []
        : [array1[i]]
    ));
}
result.push(...array1.slice(l), ...array2.slice(l));

console.log(result);

【讨论】:

  • 感谢您的建议,但是如果它们是对象,则只需删除,我想要的是仅在具有相同属性的情况下省略其中一个对象(也许是我的错,因为没有很好地描述问题)
  • 请添加不同的用例和想要的结果。
猜你喜欢
  • 2022-12-15
  • 2016-03-08
  • 2021-09-12
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2022-07-21
相关资源
最近更新 更多