gpt4 book ai didi

javascript - 检查并添加数组对象中的属性

转载 作者:行者123 更新时间:2023-11-30 20:13:00 25 4
gpt4 key购买 nike

我在下面有一个非常具体的格式详细信息的对象/输出:

result = 
AB: [ 0:{Name: "Tom", team:"Spirit", position: "Defender", score: 22 }
1:{Name: "Paul", team:"Vikings", position: "center" }
2:{Name: "Jim", team:"United", position: "Wing", }
3:{Name: "Greg", team:"Crusaders", position: "Fullback", score: 54}
4:{Name: "Tim", team:"Vikings", position: "Fullback", score: 77 }
]
CD: [0:{...},1:{...},2:{...},3:{...},4:{...}]
EF: [0:{...},1:{...},2:{...},3:{...},4:{...}]
GH: [0:{...},1:{...},2:{...},3:{...},4:{...}]

结果有嵌套数组。在某些输出中,score 的属性不存在,但我需要它存在 - 如果它不存在,我需要将其默认添加为 score:"" 如果它存在有没有然后就不管它了。

我已经能够添加 score 的属性,但只能在结果对象的顶层添加,例如

...
GH: [0:{...},1:{...},2:{...},3:{...},4:{...}]
score:""

通过

 if(result.hasOwnProperty("score")) {
alert('Item has already that property');
} else {
result.score = "" ;
}

我可以通过(下方)定位特定路径,但我想将其应用于所有路径:

 if(finalResult['AB'][1].hasOwnProperty("durabilityScore")) {
alert('Item has already that property');
} else {
finalResult['AB'][1].durabilityScore = 'value';
}

如果有帮助,我正在使用 Lodash。谢谢

最佳答案

您可以迭代对象和数组的值。然后检查该属性是否存在,如果不存在则赋值。

此解决方案不会覆盖 falsy值(0''falseundefinednull),其中如果使用默认检查就会发生,比如

o.score = o.score || ''

var result = { AB: [{ Name: "Tom", team:"Spirit", position: "Defender", score: 22 }, { Name: "Paul", team:"Vikings", position: "center" }, { Name: "Jim", team:"United", position: "Wing" }, { Name: "Greg", team:"Crusaders", position: "Fullback", score: 54 }, { Name: "Tim", team:"Vikings", position: "Fullback", score: 77 }] };

Object.values(result).forEach(a => a.forEach(o => 'score' in o || (o.score = '')));

console.log(result);
.as-console-wrapper { max-height: 100% !important; top: 0; }

关于javascript - 检查并添加数组对象中的属性,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/52200574/

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