在JavaScript中使用filter()内的filter()

时间:2017-09-25 18:00:45

标签: javascript

我有问题要过滤数据,这是我的数据:

var data = {
    CustomerInfo: [{ id : 3, name: "c" }],
    detail: {company: "Google"},
    location: {country: "Italy"},
    CustomerInfo2: [{ id : 4, name: "d" }]
};

我希望打印不是对象格式的每个名称(data[x][x] !== 'object')。例如,只打印" 公司"和" 国家/地区"。 这是我的代码:

var dataFiltered = Object.keys(data).filter(function(parent){

    return Object.keys(data[parent]).filter(function(child){
      return typeof data[parent][child] !== 'object';
    });

}).reduce(function(prev, child) {
  console.log(prev + " >>> " + data[child]);
});

我有点搞砸过滤器里面的过滤器。

最后我想要这个结果:

company >>> Google
country >>> Italy

1 个答案:

答案 0 :(得分:1)

你可以做到

var data = {
    CustomerInfo: [{ id : 3, name: "c" }],
    detail: {company: "Google"},
    location: {country: "Italy"},
    CustomerInfo2: [{ id : 4, name: "d" }]
};

let result = Object.keys(data).reduce((a, b) => {
    if(typeof data[b] == 'object'){
        for(let element of Object.keys(data[b])){
            if(typeof data[b][element] != 'object'){
                a.push(data[b][element]);
                console.log(element, '>>>', data[b][element]);
            }
        }
    }
    return a;
},[]);

console.log(result)