我有一个api,它为我提供要尝试推入数组的值。我的数组是这样的
this.rolesArr = [
{ label: 'Admin', value: '1' },
{ label: 'Manager', value: '2' },
{ label: 'Recruiter', value: '3' },
{ label: 'Operational', value: '4' }
];
我收到的数据是这样的
{1: "System Admin", 2: "Internal Account Manager", 3: "CAT Manager", 4: "HR Admin", 5: "HR Manager", 6: "HR Recruiter", 7: "Candidate", 8: "Operations administrator"}
如何将其推入数组以匹配结构?
我正在尝试但被卡住
for(let i = 0; i < roles.roles.length; i++) {
this.rolesArr.push([ { label: , value: '1' }])
}
答案 0 :(得分:2)
您可以使用Object.entries
来获取键值对作为数组,然后使用Array#map
方法来生成数组。
let data = {1: "System Admin", 2: "Internal Account Manager", 3: "CAT Manager", 4: "HR Admin", 5: "HR Manager", 6: "HR Recruiter", 7: "Candidate", 8: "Operations administrator"};
let res = Object.entries(data).map(([value, label])=>({ label, value }))
console.log(res)
要将这些值添加到现有数组中,请使用Spread syntax和Array#push
方法。
this.rolesArr.push(...res)
答案 1 :(得分:1)
您可以使用函数Object.entries
获取标签和值,然后使用函数reduce
构建所需的输出。
let obj = { 1: "System Admin", 2: "Internal Account Manager", 3: "CAT Manager", 4: "HR Admin", 5: "HR Manager", 6: "HR Recruiter", 7: "Candidate", 8: "Operations administrator"},
result = Object.entries(obj).reduce((a, [label, value]) => a.concat({label, value}), []);
console.log(result);
.as-console-wrapper { max-height: 100% !important; top: 0; }
答案 2 :(得分:1)
只需更正提供的代码即可解决问题,以便您可以识别出做错了什么。
var data = { 1: "System Admin", 2: "Internal Account Manager", 3: "CAT Manager", 4: "HR Admin", 5: "HR Manager", 6: "HR Recruiter", 7: "Candidate", 8: "Operations administrator" };
var entries = Object.entries(data);
var rolesArr = [];
for (var i = 0; i < entries.length; i++) {
this.rolesArr.push({ label: entries[0][1], value: entries[0][0] })
}
console.log(this.rolesArr);