我试图循环遍历对象的县对象,并在现有的键(雄鹿和蒙哥马利)中添加两个新属性(nameCombined& codeCombined)
我起床一直到这里。但不能变异:
Object.entries(object1).forEach((item, key) => item.map(item => console.log('item', item)));以下是数据:
const counties = {
"Bucks": {
"countyCode": "42017",
"globalStateCode": "PA",
"stateCode": "PA"
},
"Montgomery": {
"countyCode": "42091",
"globalStateCode": "PA",
"stateCode": "PA"
}
};预期结果:
"Bucks": {
"countyCode": "42017",
"globalStateCode": "PA",
"stateCode": "PA”,
nameCombined: “Bucks (PA)", // basically this the end result of => key + " (" + counties[key].stateCode + ")"
codeCombined: “42017 PA Bucks”// basically this the end result of => counties[key].countyCode + " " + counties[key].stateCode + " " + key
},
"Montgomery": {
"countyCode": "42091",
"globalStateCode": "PA",
"stateCode": "PA”,
nameCombined: “Montgomery (PA)", // basically this the end result of => key + " (" + counties[key].stateCode + ")"
codeCombined: “42091 PA Montgomery”// basically this the end result of => counties[key].countyCode + " " + counties[key].stateCode + " " + key
}发布于 2021-02-04 04:16:41
您使用entries和forEach在正确的路径上,但是如果您想要改变原始对象,那么map并不是您想要的--这既可以迭代数组中的项,又可以返回一个新的数组。相反,您可以简单地在forEach的主体中修改原始内容,如下所示:
const counties = {
"Bucks": {
"countyCode": "42017",
"globalStateCode": "PA",
"stateCode": "PA"
},
"Montgomery": {
"countyCode": "42091",
"globalStateCode": "PA",
"stateCode": "PA"
}
};
Object.entries(counties).forEach(([countyName, county]) => {
county.nameCombined = `${county.countyCode} (${county.stateCode})`;
county.codeCombined = `${county.countyCode} ${county.stateCode} ${countyName}`;
});
console.log(counties);
请注意,您可以得到一个更可爱的破坏性,以削减所有的county.someProperty以上。同样值得注意的是--如果你在变异对象的时候要小心--如果你做得太宽松,它会导致真正的调试噩梦。
编辑
针对这一问题,在评论中:
为什么
[countyName, county]在数组表示法中?
Object.entries(someObject)的输出将是一个数组,其中内部数组由原始对象和值的属性/键组成。也许可以通过实例来更好地理解这一点:
const lumberjanes = {
scientist: 'Jo',
strategist: 'Mal',
enforcer: 'April',
archer: 'Molly',
wildcard: 'Ripley',
};
console.log(Object.entries(lumberjanes));
/*
Logs:
[
['scientist', 'Jo'],
['strategist', 'Mal'],
...etc
]
*/
当我们循环这个输出时,如果我们把它写成
Object.entries(lumberjanes)
.forEach(entry => `Name: ${entry[1]}; Role: ${entry[0]}`);我们必须通过它们的索引来访问这些值,这种索引的可读性很低。如果我们可以使用毁伤将该参数分离为命名变量,然后在函数体中访问它们,如下所示:
Object.entries(lumberjanes)
.forEach(([name, entry]) => `Name: ${name}; Role: ${entry}`);https://stackoverflow.com/questions/66039241
复制相似问题