【问题标题】:is there an elegant way to add key/value to an object from an array是否有一种优雅的方法可以将键/值添加到数组中的对象
【发布时间】:2017-01-17 11:10:47
【问题描述】:

作为 angular2/typescript 项目的一部分,我有一个对象数组。这些对象包含一组来自数据库的键/值对。然后将其映射到 ui 端的表(使用 ag-grid-ng2)。

表的标题是动态的并在数据库中设置。

我的一个任务是将一组键/值映射到单个对象,如下所示:

const things = [
  {
    field: 'some_table_header', 
    humanReadable: 'Some table header'
  }
];

变成:

const anObjectFullOfThings = {
  some_table_header: 'Some table header'
};

我目前觉得我的代码可以更加优雅和简洁,即:

let anObjectFullOfThings = {};

things.forEach((thing) => {
  anObjectFullOfThings[thing.field] = thing.humanReadable;
});

我觉得必须有更好的东西,即以另一种方式映射 Object.keys 等。有没有其他方法可以将数组映射到对象键?

【问题讨论】:

    标签: javascript angular typescript ecmascript-6


    【解决方案1】:

    你所拥有的一切都很好。

    有些人会使用reduce:

    let anObjectFullOfThings = things.reduce((obj, thing) => {
        obj[thing.field] = thing.humanReadable;
        return obj;
    }, {});
    

    ...但这只是个人喜好问题,尤其是reduce 并没有真正减少任何东西,它只是在整个循环中延续同一个对象。

    【讨论】:

    • 了解你的品味。它实际上非常适合其余的实现。谢谢
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2010-12-10
    • 2023-01-20
    • 2011-03-20
    • 2022-11-13
    相关资源
    最近更新 更多