如何将对象转换为对象数组并添加键和值?
我当前的对象
{ "0": "Ann_B", "1": "Billy_P", "2": "Carly_C", "3": "David_L" }
我希望成为
[
{ "value": "Ann_B_Aii", "name": "Ann B Aii", },
{ "value": "Billy_P", "name": "Billy P" },
{ "value": "Carly_C", "name": "Carly C" },
{ "value": "David_L", "name": "David L" },
]
我使用了Object.entries
并将_替换为空格
答案 0 :(得分:2)
您可以获取值并通过获取新对象进行迭代。
var data = { 0: "Ann_B", 1: "Billy_P", 2: "Carly_C", 3: "David_L" },
result = Object.values(data).map(v => ({ id: v, name: v.replace(/_/g, ' ') }));
console.log(result);
.as-console-wrapper { max-height: 100% !important; top: 0; }
答案 1 :(得分:0)
您可以使用Object.values()
和.map()
方法:
let data = {
"0": "Ann_B",
"1": "Billy_P",
"2": "Carly_C",
"3": "David_L"
};
let result = Object.values(data)
.map(v => ({id: v, name: v.replace(/_/g, ' ')}));
console.log(result);
.as-console-wrapper { max-height: 100% !important; top: 0; }
答案 2 :(得分:0)
尝试一下(我假设d
包含您的输入对象;工作示例HERE)
Object.values(d).map(v=>({value:v,name:v.replace(/_/g,' ')}));