Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Concise object filter to array of objects

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

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

[
{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)
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading