-1

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()?

knot22
  • 2,648
  • 5
  • 31
  • 51
  • `Object.fromEntries(Object.entries(d).filter(([,v]) => v === null));`. But in your `forEach` you're just failing to assign to the `k`. `v === null && nulls[k] = v);` – pilchard Jul 28 '22 at 11:32
  • 1
    Just modify the condition in the dupe target – Andreas Jul 28 '22 at 11:37

1 Answers1

2

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)
cmgchess
  • 7,996
  • 37
  • 44
  • 62
  • @pilchard I'm curious how reduce could be used to convert it back to an object. Would you like to post an answer which demonstrates that? – knot22 Jul 28 '22 at 11:35
  • 1
    This type of question has been asked multiple times on SO. Please close these questions as duplicate instead of adding yet another copy of an already written answer... – Andreas Jul 28 '22 at 11:38
  • I had difficulty finding a similar question; thus the post. Do you have a specific link to a post that is essentially the same as this question? – knot22 Jul 28 '22 at 11:39
  • 1
    @knot22 The dupe target which I've used to close the question... o.O – Andreas Jul 28 '22 at 11:41
  • Apologies. I did not understand what was meant by "dupe target" when I read your comment under my original post. Your comment immediately above adds the missing context to understand what that meant. – knot22 Jul 28 '22 at 11:45