javascript 如何使用lodash将对象转换为数组
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/31561287/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
How to convert object into array with lodash
提问by Rakesh Kumar
I have below object
我有以下对象
{
"holdings": [
{
"label": "International",
"value": 6
},
{
"label": "Federal",
"value": 4
},
{
"label": "Provincial",
"value": 7
}
]
}
I want to convert it into below object with lodash
我想用 lodash 将它转换成下面的对象
{
"holdings": [
[
"International",
6
],
[
"Federal",
4
],
[
"Provincial",
7
],
[
"Corporate",
7
]
]
}
is there any way to change it. Please suggest.
有什么办法可以改变它。请建议。
采纳答案by thefourtheye
If you want to use only lodash, then you can do it with _.mapValues
and _.values
to get the result, like this
如果您只想使用 lodash,那么您可以使用_.mapValues
并_.values
获得结果,如下所示
console.log(_.mapValues(data, _.partial(_.map, _, _.values)));
// { holdings: [ [ 'International', 6 ], [ 'Federal', 4 ], [ 'Provincial', 7 ] ] }
The same can be written without the partial function, like this
没有偏函数也可以这样写,像这样
console.log(_.mapValues(data, function(currentArray) {
return _.map(currentArray, _.values)
}));
// { holdings: [ [ 'International', 6 ], [ 'Federal', 4 ], [ 'Provincial', 7 ] ] }
回答by Amit
This works recursively (So has to be called on the holdings
property if you want to keep that) and "understands" nested objects and nested arrays. (vanilla JS):
这递归地工作(holdings
如果你想保留它,那么必须在属性上调用)并“理解”嵌套对象和嵌套数组。(香草JS):
var source = {
"holdings": [
{
"label": "International",
"value": 6
},
{
"label": "Federal",
"value": 4
},
{
"label": "Provincial",
"value": 7
}
]
}
function ObjToArray(obj) {
var arr = obj instanceof Array;
return (arr ? obj : Object.keys(obj)).map(function(i) {
var val = arr ? i : obj[i];
if(typeof val === 'object')
return ObjToArray(val);
else
return val;
});
}
alert(JSON.stringify(ObjToArray(source.holdings, ' ')));