从JSON获取键和值

时间:2022-10-10 21:16:40

For me i have a object like var object = [{"1":"w"},{"2":"z"}] ;

对于我,我有一个对象,比如var对象= [{"1":"w"},{"2":"z"}];

While iterating other array = '[{},{},{}]' i wanted to get object key and value i.e processing at index 0 of array should give me 1 and w respectively .

在迭代其他数组= '[{},{},{}]'时,我想获得对象键和值i。在数组索引0处进行e处理,分别得到1和w。

. While seeing some other posts of stack overflow i tried with ,

。当我看到其他一些栈溢出的帖子时,

$.each(array, function(index, value) {

美元。每个(数组,函数(指数、价值){

        if(object[index] != undefined)
        {
         console.log("enterobject",$.parseJSON(JSON.stringify(object[index])));
         console.log("enterobjectValue",$.parseJSON(JSON.stringify(object[index])).key);
         console.log("enterobjectValue",$.parseJSON(JSON.stringify(object[index])).value); 

}}

} }

Only first console.log is printing like {"1":"w"} for index 0 , but not second and third log which i wanted to return me 1 and w respectively are not working .

只有第一个控制台。log打印为{"1":"w"}表示索引0,而不是第二个和第三个我想分别返回1和w的日志。

Thanks

谢谢

1 个解决方案

#1


1  

It looks like you're getting back an array. If it's always going to consist of just one element, you could do this (yes, it's pretty much the same thing as Tomalak's answer):

看起来你得到了一个数组。如果它总是由一个元素组成,你可以这么做(是的,这和托玛拉克的答案差不多):

$.each(result[0], function(key, value){
console.log(key, value);
});

If you might have more than one element and you'd like to iterate over them all, you could nest $.each():

如果您可能有多个元素,并且希望对它们进行迭代,您可以嵌套$.each():

$.each(result, function(key, value){
$.each(value, function(key, value){
    console.log(key, value);
});
});

#1


1  

It looks like you're getting back an array. If it's always going to consist of just one element, you could do this (yes, it's pretty much the same thing as Tomalak's answer):

看起来你得到了一个数组。如果它总是由一个元素组成,你可以这么做(是的,这和托玛拉克的答案差不多):

$.each(result[0], function(key, value){
console.log(key, value);
});

If you might have more than one element and you'd like to iterate over them all, you could nest $.each():

如果您可能有多个元素,并且希望对它们进行迭代,您可以嵌套$.each():

$.each(result, function(key, value){
$.each(value, function(key, value){
    console.log(key, value);
});
});