Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Convert object to array of key–value objects like `{ name: "Apple", value: "0.6" }`

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 }
]
like image 516
Iron_Man Avatar asked Dec 18 '17 06:12

Iron_Man


People also ask

How do you convert the values of an object into an array?

You can convert its values to an array by doing: var array = Object. keys(obj) . map(function(key) { return obj[key]; }); console.

How do you convert an object to a key-value pair?

To convert a JavaScript object into a key-value object array, we can use the Object. entries method to return an array with of key-value pair arrays of a given object. Then we can use the JavaScript array map method to map the key-value pair arrays into objects.

What array will you get if you convert an object to array?

If an object is converted to an array, the result is an array whose elements are the object's properties.

How do you convert a list of objects into an object?

The quickest way to convert an array of objects to a single object with all key-value pairs is by using the Object. assign() method along with spread operator syntax ( ... ). The Object.


2 Answers

 const result = Object.entries(total).map(([name, value]) => ({name, value}));
like image 125
Jonas Wilms Avatar answered Oct 21 '22 10:10

Jonas Wilms


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);
like image 28
Suren Srapyan Avatar answered Oct 21 '22 11:10

Suren Srapyan