我有一个对象列表
{
"list": {
"item": [
{
"id": "12",
"value": "abc"
},
{
"id": "34",
"value": "pqr"
}
]
}
}
并希望将其转换为地图
{"12": "abc", "34","pqr"}
最简单的方法是什么?
答案 0 :(得分:2)
myObject.list.item.forEach(function(item){
myMap[item.id] = item.value;
}
这样的事情会做到......
答案 1 :(得分:1)
for
循环是最简单的方法:
var result = {};
for (var i = 0; i < obj.list.item.length; i++) {
result[obj.list.item[i].id] = obj.list.item[i].value;
}
console.log(result);
答案 2 :(得分:1)
使用jsondecode在php或c#中使用带deserializate的类转换数组或列表(http://stackoverflow.com/questions/2546138/deserializing-json-data-to-c-sharp-using-json-网)
答案 3 :(得分:1)
我会做这样的事情:
function map(list, key, value){
var result = {};
for(i in list){
result[list[i][key]] = list[i][value];
}
return result;
}
然后用你的对象:
var list = {
"list": {
"item": [
{
"id": "12",
"value": "abc"
},
{
"id": "34",
"value": "pqr"
}
]
}
}
我可以这样调用这个函数:
map(list["list"]["item"],"id","value")
它将返回: { 12:“abc”, 34:“pqr” }