1

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"

2 Answers 2

2

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);

Sign up to request clarification or add additional context in comments.

Comments

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

Or you can also do:

services = Object.keys(jsonData)

2 Comments

Note that not all keys are shown, eg. Service, and their final values are different, eg. draincleaning becomes Drain Cleaning
True. Then for the ones he wants to rename, he can check for them with an if statement in the for loop method i listed above. Not sure of a better way other than that.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.