使用多个对象数组替换多个对象数组

时间:2017-06-13 09:17:09

标签: javascript arrays ecmascript-6

我尝试用对象数组替换或覆盖对象数组,比如

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

在arr和arr2上,属性状态等于error的对象数组的长度将始终相同。但如果我有多个对象数组

,它将无法工作
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
  }];

1 个答案:

答案 0 :(得分: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; }