Modelesq Modelesq - 6 months ago 17
JSON Question

Reduce typeof object within a parent object

I have a variable student that brings in the json response...

const student = this.props.response.student;


It returns json that looks like this:

student = {
"student_id":"229570000",
"student_app":"app_002ffjUH989JJ0",
"address":"124 Aloha Dr",
"class":{ // object
"science":"SCI132",
"mathematics":"MAT032",
"english": "PSI033",
},
... more data possibly more objects
}


I actually need to filter out the objects. As in, remove this class object and any other objects within this object. So how can I remove objects within this json response? (ES6 jsx) Thank you for your help in advance.

Answer

You can reduce student's object properties using Object.keys() and check if property value is object:

student = {
    "student_id":"229570000",
    "student_app":"app_002ffjUH989JJ0",
    "address":"124 Aloha Dr",
    "classes":{         // object
           "science":"SCI132",
           "mathematics":"MAT032",
           "english": "PSI033",
     },
}

var result = Object.keys(student).reduce((r, key) => {
    if (typeof student[key] !== 'object') {
        Object.assign(r, {
            [key]: student[key]
        });
    }
    return r;
}, {})

console.log(result);