简体   繁体   English

如何使用lodash将对象转换为数组

[英]How to convert object into array with lodash

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. 请建议。

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 ] ] }

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. 这是递归工作的(如果你想保留它,必须在holdings属性上调用)并“理解”嵌套对象和嵌套数组。 (vanilla JS): (香草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, ' '))); 

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM