简体   繁体   English

在 JavaScript object 中提取第一个非空键值对

[英]extract first not-null key-value pair in JavaScript object

Let's assume I have the following object:假设我有以下 object:

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

What I want to extract is the first not-null pair, here {c: 1} ?我要提取的是第一个非空对,这里是{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})

You can use Object.keys to get the keys of the object.您可以使用Object.keys获取 object 的密钥。 Then, use find to return the first key with a non-null value.然后,使用find返回具有非空值的第一个键。

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

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

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

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)

You can iterate over the object keys and use break to stop the loop once you find the first value which is not null.您可以遍历 object 键并在找到第一个不是 null 的值后使用 break 停止循环。 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);

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM