Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
229 views
in Technique[技术] by (71.8m points)

javascript - How to parse JSON data when the property name is not known in advance?

Here is my response code in jQuery:

var response = $.parseJSON(response);

for (var i = 0; i < response.groupIds.length; i++) {
    console.log(response.groupIds[i], i);
}

Each response.groupIds[i] is of the form {"unknown name":"unknown value"}.

I wish to access both of these bits of data in javascript, how do I accomplish this when I don't know in advance what e.g. unknown name is?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

Use Object.keys to retrieve a full list (array) of key names. A polyfill is available here.

var group = response.groupIds[i];

var allPropertyNames = Object.keys(group);
for (var j=0; j<allPropertyNames.length; j++) {
    var name = allPropertyNames[j];
    var value = group[name];
    // Do something
}

Your question's response format contains only one key-value pair. The code can then be reduced to:

var group = response.groupIds[i];
var name = Object.keys(group)[0]; // Get the first item of the list;  = key name
var value = group[name];

If you're not interested in the list, use a for-i-in loop with hasOwnProperty. The last method has to be used, to exclude properties which are inherit from the prototype.

for (var name in group) {
    if (group.hasOwnProperty(name)) {
        var value = group[name];
        // Do something
    }
}

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...