jquery - 从 ajax JSON 响应构建数组

标签 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"

最佳答案

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

相关文章:

javascript - 解析 JSON 以获取 Google News Feed 中描述的干净、纯文本

json - list 不是有效的 JSON。行 : 1, 列 : 1, 意外 token

jquery - 从 jQuery 队列出队不起作用

java - Java中通过引用删除对象

javascript - 编写 for 循环以使用数组创建多个方法

java - 如何检查 arrayList 的所有元素是否相同?

json - 如何使用 jq 从 terraform 状态文件中提取特定字段?

javascript - 向 html 元素追加/添加自定义数据(隐藏)?

javascript - 如何使用 Angular 为 js-calendar-year 中的每个选定日期添加颜色。页面刷新后颜色应该保持不变

javascript - 如何记住 jquery ajax 响应?