Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
234 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 Answer

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
    }
}

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...