gpt4 book ai didi

javascript - 将数据分配给 for 中的对象

转载 作者:行者123 更新时间:2023-11-28 12:13:54 25 4
gpt4 key购买 nike

我正在尝试将循环数据添加到对象中。

subItem.allAvgObj = {};

for(var i = 0; i < subItem.implementations.length; i++) {

if (subItem.implementations[i].avg_score) {

Object.assign(subItem.allAvgObj, {
scoreAvg: subItem.implementations[i].avg_score,
scorePonderation: subItem.implementations[i].ponderation,
})

}
}

仅,只有循环的最后一个对象被分配。

{
"scoreAvg": 8,
"scorePonderation": 10
}

我尝试使用数组,它可以工作(但它是一个具有单个值的数组,但循环可以工作)

subItem.allAvgArray.push(subItem.implementations[i].avg_score);

返回:

[
13.5,
16,
8
]

如何制作这样的对象?

{
"scoreAvg": 13.5,
"scorePonderation": 20
},
{
"scoreAvg": 16,
"scorePonderation": 20
},
{
"scoreAvg": 8,
"scorePonderation": 10
}

谢谢

最佳答案

创建对象数组的更简单方法可能是使用 .filter()删除那些没有 avg_score() 的内容,然后 .map()从每个项目创建结果对象。

let result = subItem.implementations
.filter(i => i.avg_score)
.map(i => ({
scoreAvg: i.avg_score,
scorePonderation: i.ponderation
}));

const subItem = {
implementations: [{
avg_score: 15.7,
ponderation: 20
},
{
avg_score: 0,
ponderation: 15
}, {
avg_score: 6.8,
ponderation: 10
}
]
}

let result = subItem.implementations
.filter(i => i.avg_score) //remove items without avg_score
.map(i => ({ //turn the remaining items into objects
scoreAvg: i.avg_score,
scorePonderation: i.ponderation
}));

console.log(result);

或者,reduce()一次性解决方案。

let result = subItem.implementations
.reduce((acc,i) =>
i.avg_score
? [...acc, {scoreAvg: i.avg_score, scorePonderation: i.ponderation}]
: acc
,[]);

const subItem = {
implementations: [{
avg_score: 15.7,
ponderation: 20
},
{
avg_score: 0,
ponderation: 15
}, {
avg_score: 6.8,
ponderation: 10
}
]
}

let result = subItem.implementations
.reduce((acc,i) =>
i.avg_score //if avg_score, add an object. else, do nothing.
? [...acc, {scoreAvg: i.avg_score, scorePonderation: i.ponderation}]
: acc
,[]);

console.log(result);

请注意,reduce() 解决方案在性能上弥补了可读性方面的不足。

关于javascript - 将数据分配给 for 中的对象,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/54311387/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com