GeoCom
GeoCom

Reputation: 1374

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

Upvotes: 1

Views: 54

Answers (1)

marvel308
marvel308

Reputation: 10458

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)

Upvotes: 1

Related Questions