首页 > 解决方案 > 将 2 个对象合并为一个新对象,具有选择性条件

问题描述

我正在尝试根据条件创建一组新的对象,将新组件从第二个组件添加到第一个组件。这是一个例子:

有这 2 组对象:

const one = [{code: 'a'},{ code: 'b'}, {code: 'c'}]
const two = [{code: 'b', status: 'active'}]

并希望得到如下结果:

{ code: 'a', status: 'empty' }
{ code: 'b', status: 'active' }
{ code: 'c', status: 'empty' }

这是我作为示例编写的代码:

const one = [{code: 'a'},{ code: 'b'}, {code: 'c'}]
const two = [{code: 'b', status: 'active'}]



var final = []
var temp = {}

for(let holiday of one) {
    // here I started to create a temp object with components of object one
    temp.code = holiday.code
    
    // here I check if same code from object one exist in any object two
    var checksub= two.find(o => o.code == holiday.code)

    // then assigns proper value to temp object from object two, of a default instead
    if(checksub){temp.status = checksub.status}
    else {temp.status = 'empty'}

    // then push the object into new array of objects
    final.push(temp)
}
    
console.log(final)

但我得到的结果是:

[
  { code: 'c', status: 'empty' },
  { code: 'c', status: 'empty' },
  { code: 'c', status: 'empty' }
]

为什么我得到最后一个对象的 3 倍?我尝试了不同的方法(使用 forEach 和 for 循环)并且总是得到同样奇怪的结果......我做错了什么?谢谢!!!

标签: node.jsarraysjsonobject

解决方案


您通过引用传递对象,因此如果您在一个位置更改对象的值,则使用该值的所有位置都将被更新。由于在每个循环中, temp 的值都会更改,因此您的数组会使用更新后的值进行更新。因此,如果您只是传递临时对象的克隆,那么您的所有值都不会受到影响。

const one = [{code: 'a'},{ code: 'b'}, {code: 'c'}]
const two = [{code: 'b', status: 'active'}]



var final = []
var temp = {}

for(let holiday of one) {
    // here I started to create a temp object with components of object one
    temp.code = holiday.code
    
    // here I check if same code from object one exist in any object two
    var checksub= two.find(o => o.code == holiday.code)

    // then assigns proper value to temp object from object two, of a default instead
    if(checksub){temp.status = checksub.status}
    else {temp.status = 'empty'}

    // then push the clone of object into new array of objects
    final.push({...temp})
}
    
console.log(final)

您所要做的就是final.push({...temp})解构临时对象并将其作为新对象传递。

决赛将如下:

[
 {code: "a", status: "empty"},
 {code: "b", status: "active"},
 {code: "c", status: "empty"},
]

推荐阅读