13

I have an object like this:

const total = {
    "Apple": 0.6,
    "Banana": 0.6,
    "Orange": 1,
    "Grapes": 0.4,
    "Pineapple": 0.4
  };

Now I want to convert it into an array of key–value objects where each object has the same set of two properties, "name" and "value", which hold the key and value, respectively, of each property of the original object:

[
  { "name": "Apple", "value": 0.6 },
  { "name": "Banana", "value": 0.6 },
  { "name": "Orange", "value": 1 },
  { "name": "Grapes", "value": 0.4 },
  { "name": "Pineapple", "value": 0.4 }
]
Sebastian Simon
  • 18,263
  • 7
  • 55
  • 75
Iron_Man
  • 161
  • 11
  • If you’re looking for the inverse of this: [How do I convert array of Objects into one Object in JavaScript?](/q/19874555/4642212). – Sebastian Simon Dec 01 '21 at 01:41

3 Answers3

30

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);
Passer By
  • 19,325
  • 6
  • 49
  • 96
Suren Srapyan
  • 66,568
  • 14
  • 114
  • 112
7
 const result = Object.entries(total).map(([name, value]) => ({name, value}));
Jonas Wilms
  • 132,000
  • 20
  • 149
  • 151
0

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.

BlackBeard
  • 10,246
  • 7
  • 52
  • 62