场景:我有一个变量 JSON
var json = {
"order": {
"orderDetails": [{
"a1": "b1",
"c1": "d1",
"e1": "f1"
}, {
"a1": "b2",
"c1": "d2",
"e1": "f2"
}, {
"a1": "b3",
"c1": "d3",
"e1": "f3"
}],
"orderHeader": [{
"a2": "b1",
"c2": "d1",
"e2": "f1"
}, {
"a2": "b2",
"c2": "d2",
"e2": "f2"
}]
}
};
我需要获取 order.orderdetails.a1
所有值的数组,例如
['b1', 'b2', 'b3']
最佳答案
因为你 underscore.js , lodash包括在内,为什么不利用它们而不是重新发明轮子。
单行使用_.map
怎么样? . _.map
也接受字符串作为 iteratee 并将从传递的对象返回该键的值。
_.map(json.order.orderDetails, 'a1')
var json = {
"order": {
"orderDetails": [{
"a1": "b1",
"c1": "d1",
"e1": "f1"
}, {
"a1": "b2",
"c1": "d2",
"e1": "f2"
}, {
"a1": "b3",
"c1": "d3",
"e1": "f3"
}],
"orderHeader": [{
"a2": "b1",
"c2": "d1",
"e2": "f1"
}, {
"a2": "b2",
"c2": "d2",
"e2": "f2"
}]
}
};
var result = _.map(json.order.orderDetails, 'a1');
console.log(result);
document.getElementById('result').innerHTML = JSON.stringify(result, 0, 4); // For Demo: Showing the result on the screen
<script src="https://cdnjs.cloudflare.com/ajax/libs/lodash.js/4.0.0/lodash.js"></script>
<pre id="result"></pre>
这类似于 _.pluck
在旧版本的 lodash 中。
_.pluck(json.order.orderDetails, 'a1')
在纯 JavaScript 中使用 Array#map
可以获得相同的结果。
json.order.orderDetails.map(e => e.a1)
var json = {
"order": {
"orderDetails": [{
"a1": "b1",
"c1": "d1",
"e1": "f1"
}, {
"a1": "b2",
"c1": "d2",
"e1": "f2"
}, {
"a1": "b3",
"c1": "d3",
"e1": "f3"
}],
"orderHeader": [{
"a2": "b1",
"c2": "d1",
"e2": "f1"
}, {
"a2": "b2",
"c2": "d2",
"e2": "f2"
}]
}
};
var result = json.order.orderDetails.map(e => e.a1);
console.log(result);
document.getElementById('result').innerHTML = JSON.stringify(result, 0, 4);
<pre id="result"></pre>
关于javascript - 使用任何 lodash 获取嵌套 JSON 对象的所有值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/34974445/