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}
]
here is a solution using filter and map on the object entries.
Object.entries returns an array of [key,value] pairs i.e [["a", 0], ["b", 0], ["c", 2], ["d", 1]] for this example. 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.
I would recommend reduce as it loops through the entries array only once. While in the first it has to loop separately for the filter and map stages.
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)