transform object to array with lodash

后端 未结 11 1479
旧时难觅i
旧时难觅i 2020-12-22 23:38

How can I transform a big object to array with lodash?

var obj = {
  22: {name:\"John\", id:22, friends:[5,31,55], works:{books:[],         


        
11条回答
  •  醉酒成梦
    2020-12-22 23:46

    var arr = _.map(obj)

    You can use _.map function (of both lodash and underscore) with object as well, it will internally handle that case, iterate over each value and key with your iteratee, and finally return an array. Infact, you can use it without any iteratee (just _.map(obj)) if you just want a array of values. The good part is that, if you need any transformation in between, you can do it in one go.

    Example:

    var obj = {
        key1: {id: 1, name: 'A'},
        key2: {id: 2, name: 'B'},
        key3: {id: 3, name: 'C'}
    };
    
    var array1 = _.map(obj, v=>v);
    console.log('Array 1: ', array1);
    
    /*Actually you don't need the callback v=>v if you
    are not transforming anything in between, v=>v is default*/
    
    //SO simply you can use
    var array2 = _.map(obj);
    console.log('Array 2: ', array2);

    However, if you want to transform your object you can do so, even if you need to preserve the key, you can do that ( _.map(obj, (v, k) => {...}) with additional argument in map and then use it how you want.

    However there are other Vanilla JS solution to this (as every lodash solution there should pure JS version of it) like:

    • Object.keys and then map them to values
    • Object.values (in ES-2017)
    • Object.entries and then map each key/value pairs (in ES-2017)
    • for...in loop and use each keys for feting values

    And a lot more. But since this question is for lodash (and assuming someone already using it) then you don't need to think a lot about version, support of methods and error handling if those are not found.

    There are other lodash solutions like _.values (more readable for specific perpose), or getting pairs and then map and so on. but in the case your code need flexibility that you can update it in future as you need to preserve keys or transforming values a bit, then the best solution is to use a single _.map as addresed in this answer. That will bt not that difficult as per readability also.

提交回复
热议问题