隐蔽对象成数组

时间:2018-11-26 18:07:35

标签: javascript arrays reactjs object

如何将对象转换为对象数组并添加键和值?

我当前的对象

{   "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并将_替换为空格

3 个答案:

答案 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,' ')}));