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

isolate key value pairs in array of objects that have null value

I’m trying to create a new object that contains all of the key/value pairs from an object where the values are null. Here is the code thus far –

    const d = { pp: 1700, no: 2300, co: null, ng: 4550, zx: null };
    const nulls = {};

    Object.entries(d).forEach(([k, v]) => v === null ? nulls[k]: v);
    console.log(nulls);

The desired outcome is that the nulls object contains { co: null, zx: null }; however, the code above causes nulls to be an empty object.

What needs to be modified to get the necessary output? Maybe there is a more concise approach…possibly using .filter()?

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

>Solution :

As you have mentioned filter is a possible approach and after that convert back to an object using Object.fromEntries

const d = { pp: 1700, no: 2300, co: null, ng: 4550, zx: null };


const res = Object.fromEntries(Object.entries(d).filter(([k,v]) => v===null))
console.log(res)

possible solution using reduce

 const d = { pp: 1700, no: 2300, co: null, ng: 4550, zx: null };


 const res = Object.entries(d).reduce((acc,[k,v])=> {
  if(v===null)acc[k]=v
  return acc
 },{})
 
 console.log(res)
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