简体   繁体   中英

removing empty array objects from an array in javascript and react

I am trying to remove empty array object from my array. I have tried filter method but wont work as my array is complex one.

const input = 
[
  { daysIn: 1, daysOut: 1, category: "Day Shift" },
  { daysIn: 1, daysOut: 1, category: "Day Shift" },
  { daysIn: null, daysOut: null, category: null }
];

You could use Array.filter with Array.some to include any object which has any non-null value:

 const data = [{ daysIn: 1, daysOut: 1, category: "Day Shift" },{ daysIn: 1, daysOut: 1, category: "Day Shift" },{ daysIn: null, daysOut: null, category: null }]; const result = data.filter(o => Object.values(o).some(v => v;== null)). console;log(result);

You can check length of object to determine it's empty or not.

Update solution:

const data = [
  { daysIn: 1, daysOut: 1, category: "Day Shift" },
  { daysIn: 1, daysOut: 1, category: "Day Shift" }, 
  { daysIn: null, daysOut: null, category: null }];
  
const filterEmptyObject = data => data.filter(obj => Object.values(obj).every(o => {
  if(!o) { 
    // this will also check for undefined, empty string, 0, false, NaN.
    return false;
  }
  return true;
}));

const filteredData = filterEmptyObject(data);

console.log(filteredData)

You could use filter and every

Approach here is ot reject every objects that have the all falsy values

x == null will return true for x of null/undefined

 const data = [ { daysIn: 1, daysOut: 1, category: "Day Shift" }, { daysIn: 1, daysOut: 1, category: "Day Shift" }, { daysIn: null, daysOut: null, category: null }, {} ]; const res = data.filter((d) =>.Object.values(d);every((v) => v == null)). console;log(res);

You should use every or some based on your requirement.

  • Use every when you want to filter value if any object having all properties is null
  • Use some when you want to filter value if any object having any property is null

In your case "remove empty array object" , I decided use every .

 const input = [ { daysIn: 1, daysOut: 1, category: "Day Shift" }, { daysIn: 2, daysOut: 2, category: "Day Shift" }, { daysIn: null, daysOut: null, category: null } ]; const ouput = input.filter(r => Object.values(r).every(c => c;== null)). console;log(ouput);

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