lodash - project/transform object into key value array

前端 未结 6 694
没有蜡笔的小新
没有蜡笔的小新 2020-12-05 13:10

I\'m about to use forOwn to iterate through an object\'s properties and create an array manually and can\'t helping thinking there\'s a oneliner already availab

相关标签:
6条回答
  • 2020-12-05 13:55

    You can use pairs if it fits your case:

    _.pairs({ 'barney': 36, 'fred': 40 });
    // → [['barney', 36], ['fred', 40]]
    

    Ref: https://lodash.com/docs#pairs

    0 讨论(0)
  • 2020-12-05 14:07

    In response to Ori's comment and for completeness, I've posted the _.forOwn version. It's marginally faster but you need to declare the array first (not-a-one-liner).

    var arr = [];
    _.forOwn(obj,function(item, key) {
        arr.push({ property : key, value : item});
    });
    
    0 讨论(0)
  • 2020-12-05 14:08

    If you are using lodash/fp you can use _.entries

    const a = { one: 123, two: { value: 'b' }};
    
    const pairs = _.entries(a).map(p => ({ key:p[0], value: p[1] }))
    
    console.log(pairs)
    // [
    //   {
    //     "key": "one",
    //     "value": 123
    //   },
    //   {
    //     "key": "two",
    //     "value": {
    //       "value": "b"
    //     }
    //   }
    // ]
    <script src="https://cdnjs.cloudflare.com/ajax/libs/lodash.js/4.15.0/lodash.js"></script>
    <script src="https://cdnjs.cloudflare.com/ajax/libs/lodash-fp/4.15.0/lodash-fp.js"></script>

    0 讨论(0)
  • 2020-12-05 14:14

    You don't even need lodash for that:

    var arr = Object.keys(obj).map(function(key){
      return { key: key, value: obj[key] };
    });
    
    0 讨论(0)
  • 2020-12-05 14:14

    A little bit of ES6 :

    _.map( obj, (value, key) => ({key,value}) )

    0 讨论(0)
  • 2020-12-05 14:16

    You can use lodash's _.map() with shorthand property names:

    const obj = { 
      prop1 : "value",
      prop2: { sub:1}
    };
    
    const result = _.map(obj, (value, prop) => ({ prop, value }));
    
    console.log(result);
    <script src="https://cdnjs.cloudflare.com/ajax/libs/lodash.js/4.17.2/lodash.min.js"></script>

    Or you can do it using Object#entries with Array.map() and array destructuring:

    const obj = { 
      prop1 : "value",
      prop2: { sub:1}
    };
    
    const result = Object.entries(obj).map(([prop, value]) => ({ prop, value }));
    
    console.log(result);

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