簡體   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