Jib*_* TJ 4 javascript node.js underscore.js lodash
场景:我有一个变量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"
}]
}
};
Run Code Online (Sandbox Code Playgroud)
我需要获得所有order.orderdetails.a1类似值的数组
['b1', 'b2', 'b3']
Run Code Online (Sandbox Code Playgroud)
正如你所强调的那样,包括lodash,为什么不利用它们而不是重新发明轮子.
单线使用怎么样_.map._.map也接受字符串作为iteratee,并将从传递的对象返回该键的值.
_.map(json.order.orderDetails, 'a1')
Run Code Online (Sandbox Code Playgroud)
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 screenRun Code Online (Sandbox Code Playgroud)
<script src="https://cdnjs.cloudflare.com/ajax/libs/lodash.js/4.0.0/lodash.js"></script>
<pre id="result"></pre>Run Code Online (Sandbox Code Playgroud)
这与_.pluck旧版本的lodash类似.
_.pluck(json.order.orderDetails, 'a1')
Run Code Online (Sandbox Code Playgroud)
使用纯JavaScript可以实现相同的结果 Array#map
json.order.orderDetails.map(e => e.a1)
Run Code Online (Sandbox Code Playgroud)
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);Run Code Online (Sandbox Code Playgroud)
<pre id="result"></pre>Run Code Online (Sandbox Code Playgroud)
您可以使用此代码执行此操作.
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 a1 = json.order.orderDetails.map(function(obj){ return obj.a1 });
console.log(a1);Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
7756 次 |
| 最近记录: |