gpt4 book ai didi

javascript - 我如何访问 JSON 文档中的子元素

转载 作者:行者123 更新时间:2023-12-01 01:05:23 26 4
gpt4 key购买 nike

这是我的问题,我正在尝试解析一个具有多个对象的对象,但它们不是数组中对象的形式。我的数据如下所示

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

我尝试了多种方法来访问元素下的税收类型等,但没有成功。

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

全部返回未定义

最佳答案

您可以使用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)

关于javascript - 我如何访问 JSON 文档中的子元素,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/55699221/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com