繁体   English   中英

如何在 Angular 8 中将 map 阵列转换为新的单个 object?

[英]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 object,所以最终结果应该是:

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

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

我需要在map()中更改什么?

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

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

console.log(obj);

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

 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

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

其次,您不能在 object 上拥有多个名称完全相同的属性。 我知道没有办法解决这个问题。

您可能可以通过循环执行您想要的操作:

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

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM