简体   繁体   中英

filter out undefined properties in object

I have an array consisting of objects. Here's an example :

[
{events: Array(5), conditions: {…}},
{events: Array(5), conditions: {…}}
{conditions: {…}, awaits: Array(0), events: Array(1), pid: "123"}
] 

The objects differ as you can see. Some have the property 'pid' and some don't. And thats what this question is all about.

I want to assign the ones with pid to a new array with objects that contain pid.

Lets say this array is stored in match.entries. Well here's what i've tried.

// aa = match.entries.filter(entry => {return typeof entry.pid !== 'undefined'})

This doesnt seem to work.

My entire code :

    let aa = [];

   conditionalMatches.forEach(match => {
      aa = match.entries.filter(entry => {return typeof entry.pid !== 'undefined'})
    });

Returns empty array.

Simply use array.filter((arrayItem) => arrayItem.pid) that will also work for null values. And since pid is a string type, it will consider the value as 0 but will skip for empty value as "" .

 const conditionalMatches = [ [{ events: Array(5), conditions: {} }, { events: Array(5), conditions: {} }, { conditions: {}, awaits: Array(0), events: Array(1), pid: "" }, { conditions: {}, awaits: Array(0), events: Array(1), pid: "123" } ], [{ events: Array(5), conditions: {} }, { conditions: {}, awaits: Array(0), events: Array(1), pid: "123" } ], [] ]; let aa = []; conditionalMatches.forEach(match => { let filterArr = match.filter((arrayItem) => arrayItem.pid); if(filterArr.length !== 0) { aa.push(filterArr); } }); console.log(aa); 

You should be able to use Array.filter to find the objects where pid is defined

 const array = [ {events: Array(5), conditions: {}}, {events: Array(5), conditions: {}}, {conditions: {}, awaits: Array(0), events: Array(1), pid: "123"} ]; const filteredArray = array.filter((arrayItem) => arrayItem.pid !== undefined); console.log(filteredArray); 

Based on comments below, and this really does have to happen in a for loop, you could do something more like this?

conditionalMatches.forEach(match => {
  match.entries.forEach(entry => {
    if(entry.pid){
       aa.push(entry);
    }
  })
});

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