【问题标题】:Creating key-value paired Object from array with Array.map()?使用 Array.map() 从数组创建键值对对象?
【发布时间】:2019-08-12 11:05:57
【问题描述】:
const people = ['Peter','Henry','James'];
const unqiue = ['ID_1','ID_2','ID_3'];
let map = unique.map((id, i) => {
    return { name: people[i], id: id };
  });

这让我很喜欢

{
 0: {
  person: 'peter',
  id: ID_A
 },
 1: {
  person: 'simon',
  id: ID_B
 }
}

但是,我想取回一个由 IDS 键入的对象:

{
 ID_A: {
  person: 'peter',
  id: ID_A
 },
 ID_B: {
  person: 'simon',
  id: ID_B
 }
}

我怎么能在这里做到这一点,我似乎没有想出正确的事情。我试过了,但根本不起作用:

let map = unique.map((id, i) => {
    return [id] : { name: people[i], id: id };
  });

【问题讨论】:

  • 同时发布peopleunique 变量的值

标签: javascript object key-value key-value-store


【解决方案1】:

您可以使用Object.assign 并传播映射的值。

var unique = ['ID_A', 'ID_B'],
    people = ['peter', 'simon'],
    result = Object.assign({}, ...unique.map((id, i) => ({ [id]: { name: people[i], id } })));

console.log(result);

【讨论】:

    【解决方案2】:

    在较新的环境中,一个选项是映射到Object.fromEntries

    const map = Object.fromEntries(
      unique.map((id, i) => [id, { name: people[i], id }])
    );
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2018-05-13
      • 2013-12-02
      • 2015-03-22
      • 2016-12-31
      • 2021-08-25
      • 2015-03-05
      相关资源
      最近更新 更多