I have an array like this:
const data = [
{ percent: 123, unit: -1 },
{ percent: 456, unit: 0 },
{ percent: 0, unit: 5},
{ percent: 789, unit: -3 }
];
and I'm trying to remove all properties that have 0 value, so the desired result will be like this:
var data = [
{ percent: 123, unit: -1 },
{ percent: 456 },
{ unit: 5},
{ percent: 789, unit: -3 }
];
I've tried something like this:
const newData =
data.map(e =>
Object.keys(e).forEach(key =>
e[key] === 0 && delete e[key]));
but that returns an array of undefined values.
const data = [
{ percent: 123, unit: -1 },
{ percent: 456, unit: 0 },
{ percent: 0, unit: 5},
{ percent: 789, unit: -3 }
];
const newData = data.map(e => Object.keys(e).forEach(key => e[key] === 0 && delete e[key]))
console.log(newData)
What am I doing wrong? Thanks in advance!
.filterto select only desired items developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/… In result you will get new arrayeafterObject.keys?newData = data.map(e => e.percent == 0 || e.unit == 0 ? {}: e)