andi2.2
andi2.2

Reputation: 134

extract first not-null key-value pair in JavaScript object

Let's assume I have the following object:

const obj = {
  a: null,
  b: null,
  c: 1
}

What I want to extract is the first not-null pair, here {c: 1}?

My current attempt works but is hardcoded and not dynamic:

const data = obj.a ? {a: obj.a} : (obj.b ? {b: obj.b} : {c: obj.c})

Upvotes: 1

Views: 2247

Answers (3)

Ran Turner
Ran Turner

Reputation: 18076

You can iterate over the object keys and use break to stop the loop once you find the first value which is not null. Perhaps, something like this:

const obj = {
  a: null,
  b: null,
  c: 1
}

let notNullValue;
for(let prop in obj) {
  if(obj[prop] !== null){
    notNullValue = {[prop]: obj[prop]};
    break;
  }
}

console.log(notNullValue);

Upvotes: 0

jrcamatog
jrcamatog

Reputation: 1494

You can use Object.keys to get the keys of the object. Then, use find to return the first key with a non-null value.

const obj = {
  a: null,
  b: null,
  c: 1
}

const keyWithValue = Object.keys(obj).find((key) => obj[key] !== null);

return { [keyWithValue]: obj[keyWithValue] };

Upvotes: 3

Eka Cipta
Eka Cipta

Reputation: 229

you mean like this ?

const obj = {
  a: null,
  b: null,
  c: 1
}
const data = {}

for(let key in obj) {
  if(obj[key]) data[key] = obj[key]
}
console.log(data)

Upvotes: 0

Related Questions