javascript - 将数组映射到数组的对象内

标签 javascript arrays dictionary object push

所以我有一个对象数组,其中有很多键,类似这样的东西:

[
 { id: 1,
   phoneNumber: 12345,
   name: "John",
   underLicense: true
 },
 { id: 2,
   phoneNumber: 12345,
   name: "Jane",
   underLicense: false
 }
]

我希望它看起来像这样:

[
 { listPhone: [
    { number: 12345,
      underLicense: true
    },
    { number: 12345
      underLicense: false
    }
  ]
 }
]

因此,首先我执行map(),然后将其插入listPhones

这是我的功能

  saveLicense() {
    const listPhone = this.toSend.map(x => {
      return {
          number: x.phoneNumber,
          underLicense: x.underLicense
        };
    });
    const savedPhones = [];
    savedPhones.push({listPhone: listPhone});
  }

问题是,有没有办法在map()方法中找到它,而不必在第二步中使用push

最佳答案

您可以直接映射到属性值的表达式。

saveLicense() {
    const
        savedPhones = [{ listPhone: this.toSend.map(({ phoneNumber: number, underLicense }) =>
            ({ number, underLicense })
        ) }];
}

关于javascript - 将数组映射到数组的对象内,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/64261166/

相关文章:

javascript - 更改使用工厂函数生成的嵌入式推文的字体大小

javascript - 如何从 Javascript 类构造函数中访问分配给对象的变量名称?

python - 使用带有 np.array 值的字典列表创建 DataFrame

C++ 计数图

javascript - 如何使用 UnderscoreJS 进行条件过滤

javascript - HTML 中的 "Read More"按钮自动隐藏/显示

arrays - 在 Array 上定义一个 trim 方法,删除第一个和最后一个元素

excel - VBA 字典引用

php - 数组中的唯一关联索引

java - java中将数组传递给带有数组参数的方法和var-args有什么区别?