【发布时间】:2021-09-06 00:46:42
【问题描述】:
我正在尝试根据条件创建一组新的对象,将新组件从第二个组件添加到第一个组件。这是一个例子:
拥有这 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 循环)并且总是得到同样奇怪的结果......我做错了什么? 谢谢!!!
【问题讨论】:
-
将这个
var temp = {}移到for循环中。
标签: node.js arrays json object