node.js - 将 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 循环)并且总是得到同样奇怪的结果......我做错了什么?谢谢!!!
解决方案
您通过引用传递对象,因此如果您在一个位置更改对象的值,则使用该值的所有位置都将被更新。由于在每个循环中, 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"},
]
推荐阅读
- codeigniter - 如何在codeigniter中显示包含mpdf样式的视图页面?
- python - 需要提示来提高 Python 程序的性能
- python - 特定位置的点数 - 熊猫
- javascript - 如何使 d3 时间线图表可滚动?
- copy - Google Drive:将文件夹从共享驱动器复制到自己的驱动器
- reactjs - 过滤后的数据在 React 中显示较晚
- pytorch - 展开().unfold() 和展开() 含义
- database - 根据其他字段中的值存储其他字段
- oracle - 尽管在 oracle 中成功运行,但在 UNIX 中不是有效月份错误
- offline - 离线使用 PptxGenJS