'Array filter is not working inside array of array object?
Trying to get an object whose source value is Kitchen and whose invoice files length equal to zero.
I'm using the filter method but it's not returning any value .im not sure why filter method not returns any value .
could someone help here to move forward
Thanks in advance
var data = [{
"data_id": "1",
"name": "abc",
"source":"Hall",
"sqft": "1100",
"invoiceItems":[
{
"inv_id": "1",
"price": "925",
"Files":[
{
"filename": "a",
"filepath":"zxc"
}]
},
{
"inv_id": "2",
"price": "925",
"source":"tymetrix",
"Files":[]
}
]
}, {
"data_id": "2",
"name": "def",
"source":"Kitchen",
"sqft": "1200",
"invoiceItems":[{
"inv_id": "10",
"price": "925",
"Files":[]
},
{
"inv_id": "11",
"price": "925",
"Files":[
{
"filename": "a",
"filepath":"zxc"
}]
}]
}
];
//console.log(data)
var result = data.filter(function (el) {
if(el.source == "Kitchen"){
console.log(el.invoiceItems)
el.invoiceItems.filter(function(inv){
console.log(inv.Files);
if(inv.Files.length == 0)
{
return true;
}
});
}
});
console.log("result",result)
Solution 1:[1]
You are not returning anything from the outer filter
also you can simplify your logic in this way
var data = [{
"data_id": "1",
"name": "abc",
"source": "Hall",
"sqft": "1100",
"invoiceItems": [{
"inv_id": "1",
"price": "925",
"Files": [{
"filename": "a",
"filepath": "zxc"
}]
},
{
"inv_id": "2",
"price": "925",
"source": "tymetrix",
"Files": []
}
]
}, {
"data_id": "2",
"name": "def",
"source": "Kitchen",
"sqft": "1200",
"invoiceItems": [{
"inv_id": "10",
"price": "925",
"Files": []
},
{
"inv_id": "11",
"price": "925",
"Files": [{
"filename": "a",
"filepath": "zxc"
}]
}
]
}
];
//console.log(data)
var result = data.filter((el) =>
el.source === "Kitchen" && el.invoiceItems.some(inv => inv.Files.length == 0)
);
console.log("result", result)
Solution 2:[2]
The only problem I see in your code is return key is missing
//console.log(data)
var result = data.filter(function (el) {
if(el.source == "Kitchen"){
console.log(el.invoiceItems)
return el.invoiceItems.filter(function(inv){ // here
console.log(inv.Files);
if(inv.Files.length == 0)
{
return true;
}
});
}
});
console.log("result",result)
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 | R4ncid |
| Solution 2 | Sodhi saab |
