Javascript ES6-循环对象的对象,并使用附加属性对对象进行变异
我试图循环遍历object的countries对象,并将两个新属性namecombined&codeCombined添加到现有的key Bucks和Montgomery中 我一直到这里。但不能变异:Javascript ES6-循环对象的对象,并使用附加属性对对象进行变异,javascript,ecmascript-6,Javascript,Ecmascript 6,我试图循环遍历object的countries对象,并将两个新属性namecombined&codeCombined添加到现有的key Bucks和Montgomery中 我一直到这里。但不能变异: Object.entries(object1).forEach((item, key) => item.map(item => console.log('item', item))); 以下是数据: const counties = { "Bucks": {
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
}
使用entries和forEach时,您的路径是正确的,但是如果您想要改变原始对象,那么map就不是您想要的-它的目的是迭代数组中的项,关键是返回一个新数组。相反,您可以简单地在forEach的主体中对原始进行变异,如下所示: 康斯特县={ 雄鹿:{ 国家代码:42017, 全球国家代码:PA, 州代码:PA }, 蒙哥马利:{ 国家代码:42091, 全球国家代码:PA, 州代码:PA } }; Object.EntriesCountries.forEach[countyName,county]=>{ county.nameCombined=`${county.countyCode}${county.stateCode}`; county.codeCombined=`${county.countyCode}${county.stateCode}${countyName}`; };
console.logcountries 使用entries和forEach时,您的路径是正确的,但是如果您想要改变原始对象,那么map就不是您想要的-它的目的是迭代数组中的项,关键是返回一个新数组。相反,您可以简单地在forEach的主体中对原始进行变异,如下所示: 康斯特县={ 雄鹿:{ 国家代码:42017, 全球国家代码:PA, 州代码:PA }, 蒙哥马利:{ 国家代码:42091, 全球国家代码:PA, 州代码:PA } }; Object.EntriesCountries.forEach[countyName,county]=>{ county.nameCombined=`${county.countyCode}${county.stateCode}`; county.codeCombined=`${county.countyCode}${county.stateCode}${countyName}`; };
console.logcountries;为什么[countyName,county]使用数组表示法。请原谅我的愚蠢问题。只是想弄明白为什么[countyName,county]是用数组表示法。请原谅我的愚蠢问题。只是试着去理解