Octoxan Octoxan - 4 months ago 10
Javascript Question

Iterate through a tree to check values

Trying to iterate through this tree (which I thought was an object at first) to console log the "products" key if the "stock_status" is false. Never done anything like this.

m = {
"option_labels": {
"jamocha": {
"configurable_product": {
"small_image": null,
"base_image": null
},
"products": ["12"],
"stock_status": false
},
"matte white": {
"configurable_product": {
"small_image": null,
"base_image": null
},
"products": ["13"],
"stock_status": true
},
"cool gray": {
"configurable_product": {
"small_image": null,
"base_image": null
},
"products": ["146"],
"stock_status": true
}
}
};

Answer

You can use Object.keys() and forEach loop to check stock_status

var m = {"option_labels":{"jamocha":{"configurable_product":{"small_image":null,"base_image":null},"products":["12"],"stock_status":false},"matte white":{"configurable_product":{"small_image":null,"base_image":null},"products":["13"],"stock_status":true},"cool gray":{"configurable_product":{"small_image":null,"base_image":null},"products":["146"],"stock_status":true},"princess pink":{"configurable_product":{"small_image":null,"base_image":null},"products":["147"],"stock_status":true},"key lime":{"configurable_product":{"small_image":null,"base_image":null},"products":["148"],"stock_status":true},"nautical blue":{"configurable_product":{"small_image":null,"base_image":null},"products":["149"],"stock_status":true},"slate":{"configurable_product":{"small_image":null,"base_image":null},"products":["294"],"stock_status":true}}}

Object.keys(m.option_labels).forEach(function(e) {
  var option = m.option_labels[e];
  if(option.stock_status == false) console.log(option.products)
})

If you want to return just number not array you can change console.log(option.products) to Number(option.products[0])

var m = {"option_labels":{"jamocha":{"configurable_product":{"small_image":null,"base_image":null},"products":["12"],"stock_status":false},"matte white":{"configurable_product":{"small_image":null,"base_image":null},"products":["13"],"stock_status":true},"cool gray":{"configurable_product":{"small_image":null,"base_image":null},"products":["146"],"stock_status":true},"princess pink":{"configurable_product":{"small_image":null,"base_image":null},"products":["147"],"stock_status":true},"key lime":{"configurable_product":{"small_image":null,"base_image":null},"products":["148"],"stock_status":true},"nautical blue":{"configurable_product":{"small_image":null,"base_image":null},"products":["149"],"stock_status":true},"slate":{"configurable_product":{"small_image":null,"base_image":null},"products":["294"],"stock_status":true}}}

Object.keys(m.option_labels).forEach(function(e) {
  var option = m.option_labels[e];
  if(option.stock_status == false) console.log(Number(option.products[0]))
})

Comments