transform object to array with lodash

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

提交回复
热议问题