Hello I am generating an array with objects from some outside data. Here is my code to do so:
modifyFatalitiesByCause(data) {
let array = [];
for (let x in data) {
array.push({
"name": data[x]['HarmfulEvent'],
"value": parseInt(data[x]['Deaths']),
})
}
return array;
}
This works fine and will output this data: (heres just a small chunk of a big array)
[
{name: "Injured in Vehicle (Non-Collision)", value: 1},
{name: "Fire Hydrant", value: 1},
{name: "Snow Bank", value: 0},
{name: "Cargo/Equipment", value: 0}
]
I would like to not have the objects with a value of 0
appear in my array. Will I need to remove these at the end or can I modify my for x in data
loop to only push the objects that don't have a value of 0
.
Which is the easier solution, and can anyone help with this?
Thanks!
Yes you can do a check before pushing element on array like this if(parseInt(data[x]['Deaths']) > 0
and then push non-zero values but Array.prototype.filter() seems cool to me :)
let array = [{ name: "Injured in Vehicle (Non-Collision)", value: 1 }, { name: "Fire Hydrant", value: 1 }, { name: "Snow Bank", value: 0 }, { name: "Cargo/Equipment", value: 0 } ]; result = array.filter(elm => elm.value > 0); console.log(result);
You could remove them all at the end but it would be more efficient to just not push them to your array while you're building it. Something like this:
if (parseInt(data[x]['Deaths']) { // 0 is falsey
array.push({
"name": data[x]['HarmfulEvent'],
"value": parseInt(data[x]['Deaths']),
});
}
You can simply add a check in your for
loop, Add objects in your array, whose data[x]['Deaths'])
are non-zero. Try the following:
for (let x in data) {
if(parseInt(data[x]['Deaths']) != 0){
array.push({
"name": data[x]['HarmfulEvent'],
"value": parseInt(data[x]['Deaths']),
})
}
}
It is always best to create a predicated if statement to check the validation before the business logic execute. Here is my solution to solve this problem.
modifyFatalitiesByCause(data) {
let array = [];
for (let record in data) {
if(isDeathCountZero(record, data)){
array.push({
"name": data[record]['HarmfulEvent'],
"value": parseInt(data[record]['Deaths']),
});
}
}
return array;
}
isDeathCountZero(record, data){
return (parseInt(data[record]['Deaths']) != 0);
}
try to use array filter to filter the results. refrence: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/filter
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.