减少父对象中的typeof类型

时间:2016-05-19 19:48:08

标签: javascript json

我有一个变量学生带来了json的回应......

const student = this.props.response.student;

它返回如下所示的json:

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
}

我实际上需要过滤掉对象。在中,删除此类对象和此对象中的任何其他对象。那么如何删除这个json响应中的对象呢? (ES6 jsx)感谢您的帮助。

2 个答案:

答案 0 :(得分:3)

您可以使用student减少Object.keys()的对象属性,并检查属性值是否为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);

答案 1 :(得分:1)

您可以使用Object.keys()forEach检查对象,然后delete



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

Object.keys(student).forEach((e) => {
  if(typeof student[e] == 'object' && !Array.isArray(student[e])) delete student[e];
});

console.log(student)