简体   繁体   中英

Using filter() inside the filter() in JavaScript

I have a problem to filter the data, this is my data:

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

and I want to print each name that is not the object format ( data[x][x] !== 'object' ). for example, print just the " company " and " country ". here is my code:

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

I am kind of messed up with the filter inside the filter.

at the end I want this result:

company >>> Google
country >>> Italy

You can do

 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)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM