从javascript中的数组/对象中获取特定值

时间:2016-07-13 13:42:31

标签: javascript

完全被难住了。

我有以下对象:

var stStatus = new StockStatus({
  "3":{
    "is_in_stock":false,
    "custom_status_icon":"",
    "custom_status":"Out of Stock",
    "product_id":"9",
    "stockalert":""
  },
  "5":{
    "is_in_stock":true,
    "custom_status_icon":"",
    "custom_status":"",
    "product_id":"10"
   },
  "88":{
    "is_in_stock":true,
    "custom_status_icon":"",
    "custom_status":"",
    "product_id":"296"
    }
});

正在动态创建,所以我不知道前面有3,5或88个数字。我正在试图找出如何获得3,5,88和他们的并列is_in_stock和product_id。

如果is_in_stock为false,尝试将它基本上只用于console.log product_id和3,5,88个数字

完全难倒。

2 个答案:

答案 0 :(得分:2)

您可以迭代Object.keys

var keys = Object.keys(stStatus)

应该为您提供一个包含此实例中所有键的数组。然后,您可以使用如下结果:

stStatus[keys[0]]

访问第一个字段;其余类似。

答案 1 :(得分:1)

您可以使用Object.keys获取数组中的所有键。

然后使用forEach遍历数组并将键与对象匹配。

var m ={
  "3":{
    "is_in_stock":false,
    "custom_status_icon":"",
    "custom_status":"Out of Stock",
    "product_id":"9",
    "stockalert":""
  },
  "5":{
    "is_in_stock":true,
    "custom_status_icon":"",
    "custom_status":"",
    "product_id":"10"
   },
  "88":{
    "is_in_stock":true,
    "custom_status_icon":"",
    "custom_status":"",
    "product_id":"296"
    }
}

var _keyArray = Object.keys(m)
_keyArray.forEach(function(item){
 document.write('<pre>'+(m[item]['is_in_stock'])+'</pre>')

JSFIDDLE

相关问题