如何用第二个数组覆盖第一个数组?

时间:2021-06-30 18:07:46

标签: javascript

这是数组:

const firstArr = [
  {
    id: 1,
    code: '1'
  },
  {
    id: 2,
    code: '2'
  },
  {
    id: 3,
    code: '3'
  },
]

const secondArr = [
  {
    id: 1,
    code: '1',
    bool: true,
  },
  {
    id: 2,
    code: '2',
    bool: true,
  },
]

想要的结果是:

const overwrittenArr = [
  {
    id: 1,
    code: '1',
    bool: true,
  },
  {
    id: 2,
    code: '2',
    bool: true,
  },
  {
    id: 3,
    code: '3'
  },
]

secondArr 应该用 firstArr 值覆盖 code,如果它与 firstArr 中的值完全相同,那么它应该被替换为来自secondArr。我曾尝试用 filter 做到这一点,但没有成功。

3 个答案:

答案 0 :(得分:1)

您可以使用 forEach 来像这样改变第一个数组:

const firstArr = [
  {
    id: 1,
    code: '1'
  },
  {
    id: 2,
    code: '2'
  },
  {
    id: 3,
    code: '3'
  },
]

const secondArr = [
  {
    id: 1,
    code: '1',
    bool: true,
  },
  {
    id: 2,
    code: '2',
    bool: true,
  },
]

secondArr.forEach(x => Object.assign(firstArr.find(y => y.id === x.id) || {}, x))

console.log(firstArr)

答案 1 :(得分:0)

您可以将第二个数组分配给第一个。

const
    firstArr = [{ id: 1, code: '1' }, { id: 2, code: '2' }, { id: 3, code: '3' }],
    secondArr = [{ id: 1, code: '1', bool: true }, { id: 2, code: '2', bool: true }];

Object.assign(firstArr, secondArr);

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

答案 2 :(得分:0)

Object.assign 来救援!

const firstArr = [
  {
    id: 1,
    code: '1'
  },
  {
    id: 2,
    code: '2'
  },
  {
    id: 3,
    code: '3'
  },
];

const secondArr = [
  {
    id: 1,
    code: '1',
    bool: true,
  },
  {
    id: 2,
    code: '2',
    bool: true,
  },
];

const overwrittenArr = [
  {
    id: 1,
    code: '1',
    bool: true,
  },
  {
    id: 2,
    code: '2',
    bool: true,
  },
  {
    id: 3,
    code: '3'
  },
];

let result = Object.assign(firstArr, secondArr);

alert(JSON.stringify(result) === JSON.stringify(overwrittenArr));