transform object to array with lodash

后端 未结 11 1428
旧时难觅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:41

    2017 update: Object.values, lodash values and toArray do it. And to preserve keys map and spread operator play nice:

    // import { toArray, map } from 'lodash'
    const map = _.map
    
    const input = {
      key: {
        value: 'value'
      }
    }
    
    const output = map(input, (value, key) => ({
      key,
      ...value
    }))
    
    console.log(output)
    // >> [{key: 'key', value: 'value'}])
    <script src="https://cdnjs.cloudflare.com/ajax/libs/lodash.js/4.17.4/lodash.js"></script>

    0 讨论(0)
  • 2020-12-22 23:43

    A modern native solution if anyone is interested:

    const arr = Object.keys(obj).map(key => ({ key, value: obj[key] }));
    

    or (not IE):

    const arr = Object.entries(obj).map(([key, value]) => ({ key, value }));
    
    0 讨论(0)
  • 2020-12-22 23:45

    You can do

    var arr = _.values(obj);
    

    For documentation see here.

    0 讨论(0)
  • 2020-12-22 23:46

    Object to Array

    Of all the answers I think this one is the best:

    let arr = Object.entries(obj).map(([key, val]) => ({ key, ...val }))
    

    that transforms:

    {
      a: { p: 1, q: 2},
      b: { p: 3, q: 4}
    }
    

    to:

    [
      { key: 'a', p: 1, q: 2 }, 
      { key: 'b', p: 3, q: 4 }
    ]
    

    Array to Object

    To transform back:

    let obj = arr.reduce((obj, { key, ...val }) => { obj[key] = { ...val }; return obj; }, {})
    

    To transform back keeping the key in the value:

    let obj = arr.reduce((obj, { key, ...val }) => { obj[key] = { key, ...val }; return obj; }, {})
    

    Will give:

    {
      a: { key: 'a', p: 1, q: 2 },
      b: { key: 'b', p: 3, q: 4 }
    }
    

    For the last example you can also use lodash _.keyBy(arr, 'key') or _.keyBy(arr, i => i.key).

    0 讨论(0)
  • 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);
    <script src="https://cdnjs.cloudflare.com/ajax/libs/lodash.js/4.17.4/lodash.js"></script>

    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.

    0 讨论(0)
  • 2020-12-22 23:56

    If you want some custom mapping (like original Array.prototype.map) of Object into an Array, you can just use _.forEach:

    let myObject = {
      key1: "value1",
      key2: "value2",
      // ...
    };
    
    let myNewArray = [];
    
    _.forEach(myObject, (value, key) => {
      myNewArray.push({
        someNewKey: key,
        someNewValue: value.toUpperCase() // just an example of new value based on original value
      });
    });
    
    // myNewArray => [{ someNewKey: key1, someNewValue: 'VALUE1' }, ... ];
    

    See lodash doc of _.forEach https://lodash.com/docs/#forEach

    0 讨论(0)
提交回复
热议问题