从ajax JSON响应构建数组

时间:2018-04-09 13:54:14

标签: jquery arrays json ajax api

我需要使用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"

2 个答案:

答案 0 :(得分:2)

您可以定义名称并使用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);

答案 1 :(得分:1)

for(var i in jsonData){
    services.push(i)
}

或者您也可以这样做:

services = Object.keys(jsonData)