I want to filter an objects key/value pairs to an array of objects by value, whats the most concise way to do this?
input data
{
a: 0
b: 0
c: 2
d: 1
}
output data based on any value that is not 0
[
{name:"c", value:2},
{name:"d", value:1}
]
>Solution :
here is a solution using filter and map on the object entries. First I filter out the entries without value 0 after that I map through the result array and return in the format you want
let a = { a: 0, b: 0, c: 2, d: 1}
let r = Object.entries(a).filter(([k,v]) => v!==0).map(([name,value])=>({name,value}))
console.log(r)
and a solution using reduce
here I’m checking if the value is 0 inside the loop and adding to the accumulator if it is not.
let a = {a: 0,b: 0,c: 2,d: 1}
let r = Object.entries(a).reduce((acc,[name,value]) => {
if(value !==0)acc.push({name,value})
return acc
},[])
console.log(r)