Reputation: 460
So I'm Learning javascripts array functions and found one solution too but it is using Object.fromEntries but in my angular project I have old es version and cant update it due to some reason.
so the problem is I have one array of object which is
var a =
[{
"dateOfDeposit": "2022-06-08T18:30:00.000Z",
"cNumber": 44444,
"code": "5555555",
"amount": "5,555",
"isTaxDetails": true,
"id":""
},
{
"dateOfDeposit": "2022-06-08T18:30:00.000Z",
"cNumber": 45454,
"code": "2121212",
"amount": "",
"isTaxDetails": true,
"id":""
}]
and I want to check all object should have value in all keys except key "id"
so I was using below code to achieve it
a.map((ele: any) => Object.fromEntries(
Object.entries(ele)
.filter(([key, val]) => key != "id" && val)
));
still I dont get the desired result as
[{
"dateOfDeposit": "2022-06-08T18:30:00.000Z",
"cNumber": 44444,
"code": "5555555",
"amount": "5,555",
"isTaxDetails": true,
"id":""
}]
below is the desired output
[{
"dateOfDeposit": "2022-06-08T18:30:00.000Z",
"cNumber": 44444,
"code": "5555555",
"amount": "5,555",
"isTaxDetails": true,
"id":""
}]
only one object bcz all key contains value expect id key
which is wrong. So any javascript function which can help?
Upvotes: 0
Views: 434
Reputation: 239
IMO, you are doing it right with the first way (i.e. Object.fromEntries + Object.entries + Array.filter)
There is another way which is to use Object.entries + Array.reduce to reduce your entries array into an Object.
However, in my experience, the first solution you implemented always yielded better execution time in my case so I would stick with that.
Edit: From looking at your desired output and what your current input is, here is what you want to use.
var a = [
{
"dateOfDeposit": "2022-06-08T18:30:00.000Z",
"cNumber": 44444,
"code": "5555555",
"amount": "5,555",
"isTaxDetails": true,
"id":""
},
{
"dateOfDeposit": "2022-06-08T18:30:00.000Z",
"cNumber": 45454,
"code": "2121212",
"amount": "",
"isTaxDetails": true,
"id":""
},
];
var filteredArray = a.filter((item) => Object.entries(item).every(([key, value]) => key === "id" || typeof value != "string" || value.length > 0));
console.log(filteredArray);
Upvotes: 0
Reputation: 710
You can use
var a =
[{
"dateOfDeposit": "2022-06-08T18:30:00.000Z",
"cNumber": 44444,
"code": "5555555",
"amount": "5,555",
"isTaxDetails": true,
"id":""
}, {
"dateOfDeposit": "2022-06-08T18:30:00.000Z",
"cNumber": 44444,
"code": "5555555",
"amount": "5,555",
"isTaxDetails": null,
"id":""
},
{
"dateOfDeposit": "2022-06-08T18:30:00.000Z",
"cNumber": 44444,
"code": "5555555",
"amount": "5,555",
"isTaxDetails": 0,
"id":""
}];
var result = a.filter(function(item){
return Object.entries(item).every(function([key, val]){
return key === "id" || (val != null && val !== "");
})
})
console.log(result);
Upvotes: 1