Lou_Ds
Lou_Ds

Reputation: 551

Filter out dictionary elements with specific key in a nested list

I have a nested list that looks like:

var data = [[
    {item: 'top_X', pos:1},
    {name: 'person1', value: 1},
    {name: 'person2', value: 1}
],[
    {item: 'top_Y', pos:1},
    {name: 'person1', value: 2},
    {name: 'person2', value: 2}
],[
    {item: 'top_Z', pos:1},
    {name: 'person1', value: 1}
] ];

in js, I am trying to use a lambda function that filters out each dictionary in the data list and returns the same structure but without the dictionary where item key is present.

 all = data.map(x => {
        return x; // returns the whole list
    });

    //
    fileredOutList = data.map(x => {
       return x.filter  ?? ..
    }); // Expected output list: 
 //      data = [[{name: 'person1', value: 1},
 //              {name: 'person2', value: 1}],
 //             [{name: 'person1', value: 2},
 //              {name: 'person2', value: 2}],
 //             [{name: 'person1', value: 1}]]


fileredOutListCount = data.map(x => {
   //  return x.filter  ?? .. .count()
   // return count elements after filter --> 3
});

How can I build an inline function to filter in a sub-list and return another (filtered) list and/or the count after the filtering.

Sorry for the simple question, I am new to JS and I am stuck with this simple task.

Upvotes: 0

Views: 982

Answers (1)

arizafar
arizafar

Reputation: 3122

You can check using Object.prototype.hasOwnProperty for filtering out the object which has item property.

var data = [[
    {item: 'top_X', pos:1},
    {name: 'person1', value: 1},
    {name: 'person2', value: 1}
],[
    {item: 'top_Y', pos:1},
    {name: 'person1', value: 2},
    {name: 'person2', value: 2}
],[
    {item: 'top_Z', pos:1},
    {name: 'person1', value: 1}
] ];


let out = data.map(arr => arr.filter(e => !e.hasOwnProperty('item')));
console.log(out)

Upvotes: 1

Related Questions