我试图从json结构中获取特定键的特定json值。我尝试过以下方法:
var jsonstring;
jsonstring = JSON.stringify(myjsonObjectArray);
alert(jsonstring);//giving the below json structure
jsonstring = [{
"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"
]
}, {
"key10": [100, "Key10 Value"],
"key11": [true, "It's a true value for key11"],
"key12": [null, "key12 values is Null"],
"key13": ["Testing", "Another Test Value for key13"],
"key14": [
[10, 20], "Some other testing values"
],
"key15": ["Test Name", "Name of the key15"]
}]
但我需要以下结构:
jsonstring = [{
"key01": 10,
"key02": false,
"key03": null,
"key04": "tests",
"key05": [25, 50]
}, {
"key10": 100,
"key11": true,
"key12": null,
"key13": "Testing",
"key14": [10, 20],
"key15": "Test Name"
}]
如何获得上述结构(意味着我只需要单个值,不需要结构中相应键的第二个值/多个值)?请帮助我,并提前感谢。
答案 0 :(得分:1)
答案 1 :(得分:1)
您还可以将功能性CoffeeScript与lodash / fp一起使用。
HTML:
<script src='path/to/lodash.js'></script>
<script src='path/to/lodash.fp.js'></script>
然后:
json = [
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'
]
,
key10: [100, 'Key10 Value']
key11: [true, 'It\'s a true value for key11']
key12: [null, 'key12 values is Null']
key13: ['Testing', 'Another Test Value for key13']
key14: [
[10, 20]
'Some other testing values'
]
key15: ['Test Name', 'Name of the key15']
]
convert = _.map _.mapValues _.first
alert JSON.stringify convert json
Lodash为你提供这样的问题的辅助功能。 fp变体允许您组合,主要是通过更改参数顺序。 转换行意味着“通过仅返回值的第一个元素来映射包含对象的所有值,从而映射数组中的所有值”,这正是您想要的。
试试自己: https://jsfiddle.net/