Home > Software design >  Remove from array of Object if Empty
Remove from array of Object if Empty

Time:11-01

I have a array of object ,

var  arr = [
  {qty_auth: "", resolution: "4", status: "", order: "1495"},
  {qty_sized: "1", resolution: "4", status: "", order: "1485"}
]

If first one is empty (ex:qty_auth),want to remove the object from the array on loop. The First one is dynamic key as qt_auth,qty_sized is dynamic

So the output must be

var  arr = [
  {qty_sized: "1", resolution: "4", status: "", order: "1495"}
]

CodePudding user response:

There is not particular sequence in an object in JS, but what you can do is check for the existence and filter out only the object that contain qty_auth or qty_sized and it should not be empty "". You can use filter

var arr = [
  { qty_auth: "", resolution: "4", status: "", order: "1495" },
  { qty_sized: "1", resolution: "4", status: "", order: "1485" },
];

const result = arr.filter((o) => o.qty_auth || o.qty_sized);
console.log(result);
<iframe name="sif1" sandbox="allow-forms allow-modals allow-scripts" frameborder="0"></iframe>

CodePudding user response:

try something like this

const filtered = arr.filter(({ qty_auth, qty_sized }) => (qty_auth || qty_sized));

CodePudding user response:

const arr = [ {qty_auth: "", resolution: "4", status: "", order: "1495"}, {qty_sized: "1", resolution: "4", status: "", order: "1485"} ];

const res = arr.filter(e => {
  const qtyKey = Object.keys(e).find(key => key.startsWith('qty'));
  if(qtyKey && !e[qtyKey]) return false;
  return true;
});

console.log(res);
<iframe name="sif2" sandbox="allow-forms allow-modals allow-scripts" frameborder="0"></iframe>

Note: the key order in javascript objects is undefined.

CodePudding user response:

As @EnricoMassone below pointed out, the order of objects entries here, which I iterate once I have my object from the array (the forEach loop) might not be the same as declared, so it may be a controversial method. FYI I check if the first object property is not empty and if so, I add the whole object to the array I return.

const removeEmpty = (arr) => {
    const arrToReturn = new Array();

    arr.forEach((obj) => {
        if (Object.entries(obj)[0][1] === '') continue;
        else arrToReturn.push(obj);
    });

    return arrToReturn;
}
  • Related