javascript - 循环遍历Javascript中的对象列表时如何创建新对象?
问题描述
我有一个如下所示的字符串数组
'[{"Bangalore": ["blr", "Bengaluru", "bangalore", "BANGALORE", "Bangalore"]}, {"delhi": ["del", "new delhi", "delhi", "nd", "dilli"]}]'
现在我想循环遍历每个对象并创建自己的新对象并将其存储在列表中
这就是我所做的
json_data = JSON.parse('[{"Bangalore": ["blr", "Bengaluru", "bangalore", "BANGALORE", "Bangalore"]}, {"delhi": ["del", "new delhi", "delhi", "nd", "dilli"]}]')
tuples_to_return = []
for(i=0;i<json_data.length;i++) {
for(key in json_data[i]) {
//console.log(key, json_data[i][key])
tuples_to_return.push({key: json_data[i][key].join()})
}
}
console.log(tuples_to_return)
但奇怪的部分是输出为
[ { key: 'blr,Bengaluru,bangalore,BANGALORE,Bangalore' },
{ key: 'del,new delhi,delhi,nd,dilli' } ]
为什么键被打印为字符串本身?我期待像这样的输出
[ { "Bangalore": 'blr,Bengaluru,bangalore,BANGALORE,Bangalore' },
{ "delhi": 'del,new delhi,delhi,nd,dilli' } ]
当我对 key 执行 console.log() 时
for(i=0;i<json_data.length;i++) {
for(key in json_data[i]) {
console.log(key)
}
}
然后它给了我关键值
Bangalore
delhi
那么当我尝试制作一个对象并将我的钥匙插入那里时会发生什么?
解决方案
尝试这个:
json_data = JSON.parse('[{"Bangalore": ["blr", "Bengaluru", "bangalore", "BANGALORE", "Bangalore"]}, {"delhi": ["del", "new delhi", "delhi", "nd", "dilli"]}]')
tuples_to_return = []
for(i=0;i<json_data.length;i++) {
for(key in json_data[i]) {
//console.log(key, json_data[i][key])
tuples_to_return.push({[key]: json_data[i][key].join()})
}
}
console.log(tuples_to_return)
如果您设置{key:'foo'}
,您将获得键的属性名称。如果您设置{[key]:'foo'}
,您将获得任何字符串键包含的属性名称。
我从上面的代码得到的响应是:
[
{"Bangalore":"blr,Bengaluru,bangalore,BANGALORE,Bangalore"},
{"delhi":"del,new delhi,delhi,nd,dilli"}
]
推荐阅读
- javascript - javascript:删除链表中值大于num的所有节点
- ios - 从 2021 年 4 月起,是否必须使用 Xcode12 构建 iOS 应用程序?
- maps - 等高线数据到 DEM 数据
- java - org.apache.commons.codec.binary.Base32 解码为不同字符串的相同字节数组
- python-3.x - 如何按列计算唯一值
- python - 可以在没有互联网的情况下进行泡菜和套接字连接
- c++ - 了解 ABI C++
- c++ - 多维数组打印十六进制数字而不是数组的内容
- prestashop - 无法将主题上传到 Prestashop
- imagemagick - Imagemagick 用白色替换图像中的所有颜色