javascript - 推送数组中的值以匹配特定格式

标签 javascript arrays angular

我有一个 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 syntaxArray#push方法。

this.rolesArr.push(...res)

关于javascript - 推送数组中的值以匹配特定格式,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/55732665/

相关文章:

ios - swift 删除项目后如何重新填充数组

javascript - 无法以 Angular 显示用户名

javascript - 使用 ng-content 选择基类

Javascript:了解原型(prototype)链

javascript - D3 堆积段图,按总数排序

javascript - 刷新页面后如何清除该值

javascript - Angular translate provider - 有没有办法替换一般变量?

javascript - 我是 Angularjs 新手,只是尝试填充多个 json 值,但它不起作用

javascript - 如何通过点击从数组中获取不重复的随机字符串?

c - 为什么在 C 中释放我重新分配的数组失败?