2016-07-13 10 views
-1

ここでは完全に切り詰められています。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の場合、それは基本的に唯一のproduct_idと3,5,88番号をCONSOLE.LOGために取得しようとしています。

+1

'StockStatus'には何がありますか? –

+1

これまでに何を試しましたか? 'strStatus'を使っていますか? 'StockStatus'は何をするのですか? – evolutionxbox

+0

'Object.keys'を探していますか? –

答えて

1

Object.keysを使用すると、配列内のすべてのキーを取得できます。

次に、forEachを使用して配列をループし、キーとオブジェクトを一致させます。あなたはObject.keysを反復処理することができます

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

+1

私は変数名の先頭にアンダースコアを付けるという魅力を理解していません。なぜあなたはそれを使用していますか? (あなたは間違っていない、私はちょうどそれを得ることはありません) – evolutionxbox

+1

変数名、 'document.write'、jsFiddle ...の下線。SOには、' console.log'をサポートするスタックスニペットがあります。 – Cerbrus

+0

@evolutionxboxこれはプライベート変数を表現するためのものです。これをチェックしてください[リンク](http://javascript.about.com/od/hintsandtips/a/dollar-and-underscore.htm) – brk

2

var keys = Object.keys(stStatus) 

は、このインスタンスのすべてのキーを含む配列を提供する必要があります。次のように結果を使用できます。

stStatus[keys[0]] 

最初のフィールドにアクセスするには、次のようにします。残りの部分と同様です。

関連する問題