这是我的问题,我试图解析一个具有多个对象的对象,但它们不是数组中对象的形式。我的数据看起来像这样
{ "Jurisdiction": {
"Mwd Water Stdby Chg": {
"Tax Type": "Actual",
"Tax Amount": "$10"
},
"Mosq/Fire Ant Assmt": {
"Tax Type": "Actual",
"Tax Amount": "$7"
},
"Vector Control Chg": {
"Tax Type": "Actual",
"Tax Amount": "$2"
},
"Total Of Special Assessments": {
"Tax Type": "Actual",
"Tax Amount": "$19"
}
}
我实际上正在尝试将其转换为obj数组,如
{ "Jurisdiction":[{
"Tax Name" : "Mwd Water Stdby Chg",
"Tax Type": "Actual",
"Tax Amount": "$10"
}...]
我尝试了多种方法来访问没有运气的元素下的Tax Type等。
var obj = JSON.parse(result);
var keys = Object.keys(obj.Jurisdiction);
for (var i = 0; i < keys.length; i++) {
console.log(keys[i]["Tax Type"])
console.log([keys[i]]["Tax Type"])
}
全部返回未定义
答案 0 :(得分:1)
您可以使用Object.entires()
和map()
const obj = { "Jurisdiction": {
"Mwd Water Stdby Chg": {
"Tax Type": "Actual",
"Tax Amount": "$10"
},
"Mosq/Fire Ant Assmt": {
"Tax Type": "Actual",
"Tax Amount": "$7"
},
"Vector Control Chg": {
"Tax Type": "Actual",
"Tax Amount": "$2"
},
"Total Of Special Assessments": {
"Tax Type": "Actual",
"Tax Amount": "$19"
}
}
}
let res = Object.entries(obj.Jurisdiction).map(x => ({'Tax Name':x[0],...x[1]}));
obj.Jurisdiction = res;
console.log(obj)
答案 1 :(得分:1)
将map
与Object.entries
一起使用:
const obj = {
"Jurisdiction": {
"Mwd Water Stdby Chg": {
"Tax Type": "Actual",
"Tax Amount": "$10"
},
"Mosq/Fire Ant Assmt": {
"Tax Type": "Actual",
"Tax Amount": "$7"
},
"Vector Control Chg": {
"Tax Type": "Actual",
"Tax Amount": "$2"
},
"Total Of Special Assessments": {
"Tax Type": "Actual",
"Tax Amount": "$19"
}
}
};
obj.Jurisdiction = Object.entries(obj.Jurisdiction).map(([k, v]) => ({ "Tax Name": k, ...v }));
console.log(obj);
.as-console-wrapper { max-height: 100% !important; top: auto; }
答案 2 :(得分:0)
您应该改为使用for in循环:
var obj = { "Jurisdiction": {
"Mwd Water Stdby Chg": {
"Tax Type": "Actual",
"Tax Amount": "$10"
},
"Mosq/Fire Ant Assmt": {
"Tax Type": "Actual",
"Tax Amount": "$7"
},
"Vector Control Chg": {
"Tax Type": "Actual",
"Tax Amount": "$2"
},
"Total Of Special Assessments": {
"Tax Type": "Actual",
"Tax Amount": "$19"
}
}
}
var jur = obj.Jurisdiction, j;
for(var i in jur){
j = jur[i];
console.log(i);
console.log(j['Tax Type']);
console.log(j['Tax Amount']);
console.log('-----------------------------');
}