Reputation: 147
I need to build an array from a returned JSON object using jQuery. This would be alot easier if there were a common naming convention or sub-level for these data keys, I know there's a better way to do it but my jQuery is a little rusty. Thanks!
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");
}
Gives me
["Plumbing", "Electric", "Septic", "Excavation", "Drain Cleaning", "Heating", "Cooling", "Water Quality", "Commercial"
Upvotes: 1
Views: 43
Reputation: 26854
You can define the names and use reduce
to loop thru and check if key exist on the name variable.
//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);
Upvotes: 2
Reputation: 869
for(var i in jsonData){
services.push(i)
}
Or you can also do:
services = Object.keys(jsonData)
Upvotes: 1