获取 JSON 数组中的键值
Get key values in JSON array
我试图在遍历 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
返回一个数组,所以当然你的键总是数字数组索引 - 0
、1
、2
等等。 您将无法使用哈希键在 $.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']);
相关文章:
- 将键/值数组中的对象与另一个对象(键/值)进行比较
- 对具有唯一值的对象键的数组进行排序
- 将键、值对象转换为仅值数组
- 如何将JSON数组转换为键值数组
- 使用一个键的值数组过滤多个javascript对象
- 如何将javascript对象转换为键/值数组
- 在 Javascript 中创建键 => 值数组的正确方法是什么
- 如何从 JavaScript 或 jQuery 中的键/值数组中获取值
- javascript上键/值数组的词频
- 将数组转换为键/值数组
- Javascript/jquery:从组合键值数组中获取值
- 覆盖键/值数组中的键(如果存在)
- 在JavaScript中递归地将JSON对象转换为键/值数组
- JavaScript foreach键值数组
- JavaScript 解析 JSON 并从中创建键值数组
- 动态键值数组与多个值在Javascript
- 从对象数组中获取键值数组,而不知道对象数组的格式(Javascript)
- 转换键:值数组中的简单字符串
- Javascript键值数组存储
- 传递键值数组AJAX