【问题标题】:replace multiple array of object using multiple array of object使用多个对象数组替换多个对象数组
【发布时间】:2017-06-13 09:17:08
【问题描述】:

我尝试用对象数组替换或覆盖对象数组,像这样

let arr = [{
    status: "ok"
  }, {
    status: "ok"
  }, {
    status: "error"
  }],
  arr2 = [{
    status: "error",
    msg: "im first msg",
    "more property": true
  }];

arr = arr.map(a => {
  let fullObj = arr2.find(a2 => a2.status === a.status);
  return fullObj ? fullObj : a;
});

console.log(arr); //working

属性状态等于error的对象数组的长度在arr和arr2上总是相同的。但如果我有多个对象数组,它将不起作用

let arr = [{
    status: "ok"
  }, {
    status: "ok"
  }, {
    status: "error"
  }, {
    status: "error"
  }],
  arr2 = [{
    status: "error",
    msg: "im first msg",
    "more property": true
  }, {
    status: "error",
    msg: "im the second msg",
    "more property": true
  }];

【问题讨论】:

  • 输出应该是什么?连接消息?
  • 这个question怎么样?如果需要用多个对象替换,则需要多个对象和一个条件,应该使用哪个对象。
  • 第三个错误应该怎么办?
  • 第三个错误是什么?
  • @Weedoze 将 arr2 的对象数组替换为 arr 的对象数组

标签: javascript arrays ecmascript-6


【解决方案1】:

您可以移动错误数组并将其作为项目的值。

let arr = [{ status: "ok" }, { status: "ok" }, { status: "error" }, { status: "error" }],
    arr2 = [{ status: "error", msg: "im first msg", "more property": true }, { status: "error", msg: "im the second msg", "more property": true }];
    
arr.forEach((a, i, aa) => {
    if (a.status === 'error') {
        aa[i] = arr2.shift();
    }
});

console.log(arr);
.as-console-wrapper { max-height: 100% !important; top: 0; }

【讨论】:

  • 在我看来像个黑客。
  • 我做了另一种方法:arr.filter(obj => obj.status !== "error").concat(arr2)
  • 它改变了数组中对象的顺序。
猜你喜欢
  • 2020-06-17
  • 2013-01-27
  • 2020-10-04
  • 2018-10-03
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2021-11-07
  • 1970-01-01
相关资源
最近更新 更多