首页 > 解决方案 > 循环遍历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

那么当我尝试制作一个对象并将我的钥匙插入那里时会发生什么?

标签: javascript

解决方案


尝试这个:

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"}
]

推荐阅读