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

2
  • 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); Commented Jul 28, 2022 at 11:32
  • 1
    Just modify the condition in the dupe target Commented Jul 28, 2022 at 11:37

1 Answer 1

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)

Sign up to request clarification or add additional context in comments.

5 Comments

@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?
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...
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 The dupe target which I've used to close the question... o.O
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.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.