简体   繁体   中英

Insert object on array in key value format

I have an object set like this

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

for that, first, I will check the length of the object.

var len = Object.keys(total).length;

Now I want to convert it into proper object key-value format under array. Something Like this:

[
   {'name': 'Apple', 'value': 0.6},
   {'name': 'Banana', 'value': 0.6},
   {'name': 'Orange', 'value': 1},
   {'name': 'Grapes', 'value': 0.4},
   {'name': 'Pineapple', 'value': 0.4}
]

Now I don't know how to do code for solving the problem like this. Any help is Appreciated

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

 const result = Object.entries(total).map(([name, value]) => ({name, value}));

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 .

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM