【问题标题】:How to overwrite the first array with the second one? [duplicate]如何用第二个数组覆盖第一个数组? [复制]
【发布时间】:2021-09-12 21:40:06
【问题描述】:

这是数组:

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 应该用code 值覆盖firstArr,如果它与firstArr 中的值完全相同,那么它应该被secondArr 中的对象替换。我尝试使用filter 来做这件事,但没有成功。

【问题讨论】:

标签: javascript


【解决方案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)

【讨论】:

  • Object.assign 的使用方式很有趣,所以这是实现这一目标的最佳方式吗?
  • 我猜是这样,如果您不介意覆盖两个对象之间潜在的冲突属性
【解决方案2】:

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

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; }

【讨论】:

  • 骗,骗骗。也包括你的答案
  • 之所以有效,是因为项目已排序,secondArr 更短,没有丢失的 id,并且除了 bool 之外的对象属性相同
【解决方案3】:

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));

【讨论】:

    猜你喜欢
    • 2012-03-31
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2020-09-01
    • 2013-03-03
    • 2021-03-20
    • 2022-11-16
    相关资源
    最近更新 更多