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