可能重复:
Accessing elements of JSON object without knowing the key names
我在json下面有这个。使用这个我需要迭代这个并推送到数组作为键值,麻烦的是这个json将在运行时出现,我不知道密钥的名称。
MethodParam : [
{MaxNumberOfDomains : '10'},
{NextToken : '1'}
]
请告知
感谢
答案 0 :(得分:0)
这是一种做法。
// First, let's have some variables and your example object/json:
var i, l, key, item = [ {keyOne: 10}, {keyTwo: 'string', keyThree: false} ];
// The example you provided is an array, so we first loop that array of objects/json objects
for (i = 0, l = item.length; i < l; i++) {
// Now, let's see all the keys in the current object
console.log('Iterating array ' + (i + 1));
for (key in item[i]) {
console.log(key);
}
}
当我在节点v0.6.11中运行它时,我得到了这个:
node
> // First, let's have some variables and your example object/json:
undefined
> var i, l, key, item = [ {keyOne: 10}, {keyTwo: 'string', keyThree: false} ];
undefined
> // The example you provided is an array, so we first loop that array of objects/json objects
undefined
> for (i = 0, l = item.length; i < l; i++) {
... // Now, let's see all the keys in the current object
... console.log('Iterating array ' + (i + 1));
... for (key in item[i]) {
..... console.log(key);
..... }
... }
Iterating array 1
keyOne
Iterating array 2
keyTwo
keyThree
undefined
>