如何将数组映射到 Angular 8 中的新单个对象?

How to map array to new single object in Angular 8?

我正在这样做:

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() 中更改什么?

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

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

console.log(obj);

你不应该做任何事情来获得你想要的结果。首先,当您 运行 对数组进行映射时,将返回一个新数组。要更改它,您必须自己重新编写 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 永远是唯一的吗?

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}
}, {});

我认为这是数组 reduce 的用例:

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