lodash - project/transform object into key value array

前端 未结 6 703
没有蜡笔的小新
没有蜡笔的小新 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 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);

    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);

提交回复
热议问题