获取 JSON 数组中的键值

Get key values in JSON array

本文关键字:键值 数组 JSON 获取      更新时间:2023-09-26

我试图在遍历 JSON 数组时获取 JSON 数组中每条记录的键值。目前我有一个简单的 JSON 对象,如下所示:

 "users": {
    "key_11": {
      "text": "11"
    },
    "key_22": {
      "text": "22"
    },
    "key_33": {
      "text": "33"
    }
 }

我当前的脚本使用"map"方法将此 JSON 对象转换为可循环数组:

var user_profiles_array = $.map(user_profiles_string, function(el) { return el; });
for (var xt = 0; xt < user_profiles_array.length; xt++) {
    console.log(user_profiles_array[xt].text); //11 or 22 
}

我的问题是,如何获取例如:"key_11"或"key_22"的值?

谢谢!

您可以使用

Object.keys 获取所有对象键的数组。 拥有该数组后,您可以根据需要使用 Array.forEach 对其进行迭代:

Object.keys(usersObject).forEach(function(key, keyIndex) {
  console.log("index:",keyIndex,"key:",key,"value:",usersObject[key]);
});

但!

您在此处的特定问题是由使用 $.map 而不是 JSON.parse 引起的。 $.map返回一个数组,所以当然你的键总是数字数组索引 - 012等等。 您将无法使用哈希键在 $.map 返回的数组中查找内容。 此外,从您的变量名称来看,您在字符串上调用$.map,这绝对不会做您想要的。 假设你弄清楚了这部分,并且你以某种方式得到了一个有效的 JavaScript 对象,并且由于某种原因你仍然需要使用$.map(),你可以做的是这样的:

// $.map will return an array...
$.map(user_profiles_object, function(objVal, objKey) {
    // ...and each item in that array will be an object with a
    // property named 'key' and a property named 'val'
    return {
      key: objKey,
      val: objVal
    };
}).forEach(function(arrayObj) {
    // now each item in the array created above will be an object
    // created by your callback function:
    console.log(arrayObj.key,":",arrayObj.val);
});

你也可以依靠 Js 的 foreach。

// JSON string must be valid. Enclose your JSON in '{}' (curly braces);
var user_profiles_string =  '{ "users": { "key_11": { "text": "11" }, "key_22": { "text": "22" }, "key_33": { "text": "33" }}}';
var user_profiles_array  = JSON.parse(user_profiles_string); 
// For retrieval in loop, the Js foreach asigns the key to index param (i in this case).
for (i in user_profiles_array.users) {
    // i is the key of the user currently iterated.
    console.log('Key name is: ' + i);
    // Use i as the index to retrieve array value.
    console.log(user_profiles_array.users[i]);
}
// For direct retrieval using any given known key:
console.log(user_profiles_array.users['key_11']);