【问题标题】:How to map array to new single object in Angular 8?如何将数组映射到Angular 8中的新单个对象?
【发布时间】:2020-12-14 12:32:55
【问题描述】:

我正在这样做:

const rawValues = this.filterList.map(s => {
     return {[s.filterLabel]: s.selectedOption}
  });

filterList 变量有这种类型:

export interface SelectFilter {
  filterLabel: string;
  options: Observable<any>;
  selectedOption: string;
}

现在rawValues 被映射成这样:

[
{filterLabel: selectedOption},
{filterLabel: selectedOption},
{filterLabel: selectedOption}
]

所以这是我的新对象的数组,

但我想要的是一个 SINGLE 对象,所以最终结果应该是:

{
filterLabel: selectedOption,
filterLabel: selectedOption,
filterLabel: selectedOption
}

请注意,“filterLabel”将始终是唯一的。

我需要在map() 中进行哪些更改?

【问题讨论】:

    标签: javascript angular angular8


    【解决方案1】:

    对于这个用例,不需要映射,因为它会导致创建一个不必要的新数组。只需遍历数组中的每个元素,然后将每个 filterLabel 作为新键分配给 obj,如下所示:

    const obj = {};
    this.filterList.forEach(s => {
      obj[s.filterLabel] = s.selectedOption;
    });
    
    console.log(obj);
    

    【讨论】:

    • 这确实输出了我需要的东西....我真的认为出于某种原因我必须使用 Map()...谢谢
    • const 在这种情况下是个坏主意!使用 var 或 let
    • @i-HmD 你有什么建议?
    • const 不会限制向对象添加新键:P
    • @AJ989 let or var
    【解决方案2】:

    我认为这是数组缩减的用例:

    let result =
    [{filterLabel: 'label1', selectedOption: 'option1'}, {filterLabel: 'label2', selectedOption: 'option2'}, {filterLabel: 'label3', selectedOption: 'option3'}, {filterLabel: 'label4', selectedOption: 'option4'} ]
    .reduce(function(previousValue, currentValue, index, array) {
      return { 
        [currentValue.filterLabel]: currentValue.selectedOption,
        ...previousValue }
    }, {});
    console.log(result);

    更多详情: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/Reduce

    【讨论】:

      【解决方案3】:

      你不应该做任何事情来获得你想要的结果。首先,当您在数组上运行映射时,会返回一个新数组。要改变这一点,你必须用你自己的重新编写 map 函数。技术上可行,但不推荐。

      其次,您不能在一个对象上拥有多个具有完全相同名称的属性。我不知道有什么办法。

      你也许可以用循环做一些你想做的事情:

      let rawValues = {};
      for (i = 0; i < filterList.length; i++) { 
        rawValues[`${filterList[i].filterLabel}${i}`] =  filterList[i].selectedOption;
      }
      

      这应该给你这样的东西:

      {
         filterLabel1: selectedOption,
         filterLabel2: selectedOption,
         filterLabel3: selectedOption
      }
      

      你能保证 filterLabel 永远是唯一的吗?

      【讨论】:

      • 你可能错过了一些细节,首先,我指定对象名称是唯一的,我只是为了示例而使用相同的名称
      • 下面的用户提供了一个可行的解决方案,与您的类似,都是使用 ForEach 代替!
      • 我的错;我错过了独特的免责声明。我被无效的对象卡住了。 For 循环应该做你需要做的事情。
      【解决方案4】:
      var result = {};
      this.filterList.forEach(s => {
        result[s.filterLabel] = s.selectedOption;
      });
      

      你可以使用reduce来达到同样的效果:

      var result = this.filterList.reduce((prev, next) => {
        return {...prev, [next.filterLabel]:next.selectedOption}
      }, {});
      

      【讨论】:

        猜你喜欢
        • 2016-12-13
        • 2019-10-17
        • 2023-03-17
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2021-04-20
        • 2018-12-14
        • 2015-06-25
        相关资源
        最近更新 更多