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"}
]
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);
EDITED: If you want to filter the objects which starts with qty and which is empty then you can do as:
var arr = [
{ qty_auth: "", resolution: "4", status: "", order: "1495" },
{ qty_sized: "1", resolution: "4", status: "", order: "1485" },
];
const result = arr.filter((o) =>
Object.keys(o).some((k) => k.startsWith("qty") && o[k])
);
console.log(result);
Array#filter, iterate over the arrayqty_. You can do this using Object#keys, Array#find, and String#startsWith. If the key exists but its value is empty, return falseconst 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);
Note: the key order in javascript objects is undefined.
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;
}