如何获取json结构中键的单个特定值
How to get single specific values for keys in json structure?
我正在做一些练习,比如:
var jsonres;
jsonres = JSON.stringify(jsonObjectArray);
alert(jsonvals); // getting the below json structure
jsonres = {
"key01": [10, "Key01 Description"],
"key02": [false, "It's a false value"],
"key03": [null, "Testing Null"],
"key04": ["tests", "Another Test Value"],
"key05": [[25, 50], "Some testing values"]
}
但我需要像:
jsonres = {
"key01": 10,
"key02": false,
"key03": null,
"key04": "tests",
"key05": [25,50]
}
我如何才能获得上述结构(意味着我只需要单个值,不需要第二个值/各个键的多个值)?请帮助我,并提前表示感谢。
尝试
for(var key in jsonres) {
jsonres[key] = jsonres[key][0];
}
这是一把小提琴https://jsfiddle.net/Lzb1dum3/
var jsonres = {
"key01": [10, "Key01 Description"],
"key02": [false, "It's a false value"],
"key03": [null, "Testing Null"],
"key04": ["tests", "Another Test Value"],
"key05": [[25, 50], "Some testing values"]
}
for(var key in jsonres){
if(jsonres.hasOwnProperty(key)){
jsonres[key] = jsonres[key][0];
}
}
console.log(jsonres)
https://jsfiddle.net/xd4nwc0m/
运行此程序并查看它是否生成您想要的内容:
var jsonres = {
"key01": [10, "Key01 Description"],
"key02": [false, "It's a false value"],
"key03": [null, "Testing Null"],
"key04": ["tests", "Another Test Value"],
"key05": [[25, 50], "Some testing values"]
}
for (var key in jsonres) {
jsonres[key] = jsonres[key][0];
alert(jsonres[key]);
}
只有一行代码用于迭代密钥和分配:
var jsonres = {
"key01": [10, "Key01 Description"],
"key02": [false, "It's a false value"],
"key03": [null, "Testing Null"],
"key04": ["tests", "Another Test Value"],
"key05": [[25, 50], "Some testing values"]
}
Object.keys(jsonres).forEach(function (k) { jsonres[k] = jsonres[k][0]; });
document.write('<pre>' + JSON.stringify(jsonres, 0, 4) + '</pre>');
像这样尝试
var editer = angular.module('editer', []);
function myCtrl($scope) {
$scope.jsonres = {
"key01": [10, "Key01 Description"],
"key02": [false, "It's a false value"],
"key03": [null, "Testing Null"],
"key04": ["tests", "Another Test Value"],
"key05": [[25, 50], "Some testing values"]
}
angular.forEach($scope.jsonres, function(value,key){
$scope.jsonres[key] = value[0];
});
console.log($scope.jsonres);
}
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.23/angular.min.js"></script>
<div ng-app="editer" ng-controller="myCtrl" class="container">
<pre >{{jsonres|json}}</pre>
</div>
相关文章:
- Javascript,有没有一种方法可以将数组写成没有逗号或空格的单个文本字符串
- 如何使用javascript获取嵌套对象中所有子对象的单个属性
- 是否可以禁用jquery中的单个单选按钮
- 更改JSON对象的结构
- 引导程序:在导航栏中,显示悬停在单个位置的基于Li Link的不同内容
- 角度控制器结构
- 如何将chrome扩展功能移植到移动设备(特别是jquery和trello)
- 从键值结构中获取数据,并将其与AngularJS中ng重复的值进行比较
- 使用jquery选中/取消选中单个复选框
- 单个页面上有多个标记表单
- 在不破坏未定义函数的情况下,对多个视图使用单个js文件
- 用于多个类事件Jquery的单个函数
- 使用递归属性迭代保留属性结构
- 如何获取json结构中键的单个特定值
- Dropzone.js-上传文件夹结构和单个文件
- TypeScript 1.8,多个.ts文件中的单个文件-应用程序结构
- jQuery单个脚本文件不是特定于*this*页面-显示“;undefined不是函数”;
- 推特引导程序中模态窗口的层次结构
- d3.pack具有单个JSON的多个层次结构
- 推特引导 3 文件结构混乱