Insert object on array in key value format

前端 未结 3 1141
失恋的感觉
失恋的感觉 2021-01-01 22:49

I have an object set like this

var total = { \'Apple\': 0.6,
              \'Banana\': 0.6,
              \'Orange\': 1,
              \'Grapes\': 0.4,
             


        
相关标签:
3条回答
  • 2021-01-01 23:21

    Array#reduce can also be used to "Insert object on array in key value format":

    var total = { 'Apple': 0.6, 'Banana': 0.6, 'Orange': 1, 'Grapes': 0.4, 'Pineapple': 0.4 };
    
    var objArr = Object.entries(total)
                       .reduce((accumulator, [name, value]) => {
                          return accumulator.concat({name: name, value: value});  // creates an array of objects
                         }, [])
                       .sort((a, b) => b.value - a.value);  // sorting in descending order
    
    console.log(objArr);

    For more info read Object#entries, Array#sort and object destructuring.

    0 讨论(0)
  • 2021-01-01 23:40
     const result = Object.entries(total).map(([name, value]) => ({name, value}));
    
    0 讨论(0)
  • 2021-01-01 23:43

    You can use Array#map function on the object keys and create your objects with desired shape.

    const total = { 
        'Apple': 0.6,
        'Banana': 0.6,
        'Orange': 1,
        'Grapes': 0.4,
        'Pineapple': 0.4 
    };
                  
    const array = Object.keys(total)
                        .map(key => ({ name: key, value: total[key] }))
                        .sort((f, s) => f.value - s.value);
    
    console.log(array);

    If you use ES7 or higher you can replace Object#keys with Object#entries. Use also object destructuring in the parameter list to get name and value separately.

    const total = { 
        'Apple': 0.6,
        'Banana': 0.6,
        'Orange': 1,
        'Grapes': 0.4,
        'Pineapple': 0.4 
    };
                  
    const array = Object.entries(total)
                        .map(([name, value]) => ({ name, value }))
                        .sort((f, s) => f.value - s.value);;
    
    console.log(array);

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