0

I need to get the key that has the value > 0 in this example would be 005340302403, how could I do that?

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
Heretic Monkey
  • 11,687
  • 7
  • 53
  • 122

3 Answers3

2

You can make use of Object.keys and Array.find to get the single key from the object.

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)

To get all the keys from the object with value > 0, then Array.filter can be used. The resultant of this operation is an array.

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)
Nithish
  • 5,393
  • 2
  • 9
  • 24
1

You can use Object.entries for this.

const result = Object.entries(json.productSkuInventoryStatus).filter(item => item[1] > 0).map(item => item[0]);
console.log(result);
Derek Wang
  • 10,098
  • 4
  • 18
  • 39
0

You can also loop through object keys like this, just another approach

let greater = "";
for(let prop in json.productSkuInventoryStatus){
  if(json.productSkuInventoryStatus[prop] > 0) greater = prop;
}
console.log(greater);
Rocco
  • 145
  • 1
  • 1
  • 8