我有一个 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' }])
}
最佳答案
您可以使用 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)
关于javascript - 推送数组中的值以匹配特定格式,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/55732665/