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 }
]
1

3 Answers 3

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

Sign up to request clarification or add additional context in comments.

2 Comments

Seriously Awsome and really fast. Now If I want the result on Decreasing value order format then how I can achieve this?
You need to add sort function into the chain.
7
 const result = Object.entries(total).map(([name, value]) => ({name, value}));

1 Comment

A little explanation goes a long way.
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.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.