我需要使用 jQuery 从返回的 JSON 对象构建一个数组。如果这些数据键有一个通用的命名约定或子级别,这会容易得多,我知道有更好的方法来做到这一点,但我的 jQuery 有点生疏。谢谢!
JSON
{
"Service": true,
"ZipCode": "02865",
"City": "Lincoln",
"State": "RI",
"plumbing": true,
"electric": true,
"septic": true,
"excavation": true,
"draincleaning": true,
"heating": true,
"cooling": true,
"waterquality": true,
"commercial": true
}
jQuery
if (response.hasOwnProperty("plumbing")){
services.push("Plumbing");
}
if (response.hasOwnProperty("electric")){
services.push("Electric");
}
if (response.hasOwnProperty("septic")){
services.push("Septic");
}
if (response.hasOwnProperty("excavation")){
services.push("Excavation");
}
if (response.hasOwnProperty("draincleaning")){
services.push("Drain Cleaning");
}
if (response.hasOwnProperty("heating")){
services.push("Heating");
}
if (response.hasOwnProperty("cooling")){
services.push("Cooling");
}
if (response.hasOwnProperty("waterquality")){
services.push("Water Quality");
}
if (response.hasOwnProperty("commercial")){
services.push("Commercial");
}
给我
["Plumbing", "Electric", "Septic", "Excavation", "Drain Cleaning", "Heating", "Cooling", "Water Quality", "Commercial"
最佳答案
您可以定义名称并使用reduce
循环并检查名称变量上是否存在键。
//List the names on an object. eg use key waterquality for "Water Quality"
let name = {"plumbing": "Plumbing","electric": "Electric","septic": "Septic","excavation": "Excavation","draincleaning": "Drain Cleaning","heating": "Heating","cooling": "Cooling","waterquality": "Water Quality","commercial": "Commercial"}
//Your object
let obj = {"Service": true,"ZipCode": "02865","City": "Lincoln","State": "RI","plumbing": true,"electric": true,"septic": true,"excavation": true,"draincleaning": true,"heating": true,"cooling": true,"waterquality": true,"commercial": true}
let services = Object.keys(obj).reduce((c, v) => {
if (name[v]) c.push(name[v]);
return c;
}, []);
console.log(services);
关于jquery - 从 ajax JSON 响应构建数组,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/49734688/