Insert object on array in key value format

时间:2017-12-18 06:38:50

标签: javascript arrays

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

3 个答案:

答案 0 :(得分:31)

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

答案 1 :(得分:5)

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

答案 2 :(得分:0)

enter image description here也可用于“以键值格式在数组上插入对象”:

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

有关更多信息,请阅读Array#reduceObject#entriesArray#sort