1

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
4
  • The filter callback is expected to return a boolean. Not an array like your inner filter Commented Sep 25, 2017 at 18:03
  • Wouldn't it be easier to just test Array.isArray? Commented Sep 25, 2017 at 18:03
  • @Bergi no because you can also access properties of objects with foo[bar] Commented Sep 25, 2017 at 18:13
  • @Kristianmitk You can do that on strings as well, so no difference there. I'm not sure what your actual goal is, the distinction in your example would work if Array.isArray just fine. Commented Sep 25, 2017 at 18:17

1 Answer 1

1

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)

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.