以键值格式在数组上插入对象 [英] Insert object on array in key value format
问题描述
我有一个像这样的对象
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
推荐答案
你可以使用 Array#map 功能,并根据需要创建对象形状。
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);
如果你使用 ES7 或更高版本,您可以替换使用对象#键 noreferrer> <强>对象#条目强> 。还可以使用 对象解构 在参数列表中单独获取 name
和 value
。
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);
这篇关于以键值格式在数组上插入对象的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!