我需要获取值> 0的密钥[重复]
Posted
技术标签:
【中文标题】我需要获取值> 0的密钥[重复]【英文标题】:I need to get the key that has the value > 0 [duplicate] 【发布时间】:2021-01-08 21:42:07 【问题描述】:在本例中,我需要获取值 > 0 的键是 005340302403,我该怎么做?
var json =
"productSkuInventoryStatus":
"005340304004": 0,
"005340304003": 0,
"005340304002": 0,
"005340304001": 0,
"005340302401": 0,
"005340302402": 0,
"005340301401": 0,
"005340304005": 0,
"005340301403": 0,
"005340302405": 0,
"005340301402": 0,
"005340301405": 0,
"005340302403": 1,
"005340301404": 0,
"005340302404": 0
var array1 = Object.values(json.productSkuInventoryStatus);
const found = array1.find(element => element > 0);
console.log(found)// get de value > 0
// how to get the key of this value greater than 0
【问题讨论】:
使用 Object.entries 你会得到 [key,value] 对。现在你可以得到这两个值了。 【参考方案1】:您可以使用Object.keys
和Array.find
从对象中获取单个键。
var json =
"productSkuInventoryStatus":
"005340304004": 0,
"005340304003": 0,
"005340304002": 0,
"005340304001": 0,
"005340302401": 0,
"005340302402": 0,
"005340301401": 0,
"005340304005": 0,
"005340301403": 0,
"005340302405": 0,
"005340301402": 0,
"005340301405": 0,
"005340302403": 1,
"005340301404": 0,
"005340302404": 0
const result = Object.keys(json.productSkuInventoryStatus).find(key => json.productSkuInventoryStatus[key] > 0);
console.log(result)
要从带有value > 0
的对象中获取所有键,则可以使用Array.filter
。此操作的结果是一个数组。
var json =
"productSkuInventoryStatus":
"005340304004": 0,
"005340304003": 0,
"005340304002": 0,
"005340304001": 0,
"005340302401": 0,
"005340302402": 0,
"005340301401": 0,
"005340304005": 0,
"005340301403": 0,
"005340302405": 0,
"005340301402": 0,
"005340301405": 0,
"005340302403": 1,
"005340301404": 0,
"005340302404": 0
const result = Object.keys(json.productSkuInventoryStatus).filter(key => json.productSkuInventoryStatus[key] > 0);
console.log(result)
【讨论】:
【参考方案2】:您可以为此使用Object.entries
。
const result = Object.entries(json.productSkuInventoryStatus).filter(item => item[1] > 0).map(item => item[0]);
console.log(result);
【讨论】:
【参考方案3】:你也可以像这样遍历对象键,只是另一种方法
let greater = "";
for(let prop in json.productSkuInventoryStatus)
if(json.productSkuInventoryStatus[prop] > 0) greater = prop;
console.log(greater);
【讨论】:
以上是关于我需要获取值> 0的密钥[重复]的主要内容,如果未能解决你的问题,请参考以下文章