簡體   English   中英

如何按鍵對對象數組進行分組並在其中創建另一個 object

[英]How can I group an array of objects by key and create another object inside

有誰知道如何通過 object 鍵對對象數組進行分組,然后根據分組創建一個新的對象數組? 例如,我有一個如下所示的 Build 對象數組,我想按產品分組並創建另一個 colors 的 object 和基於此的價格。

build = [
    {
        'Product': 'Cabinets',
        'Color': 'Blue',
    }, 
    {
        'Product': 'CounterTop',
        'Color': 'White',
    }, 
    {
        'Product': 'Cabinets',
        'Color': 'Yellow',
    }, 
    {
        'Product': 'Cabinets',
        'Color': 'Yellow',
    }
]

我想要這樣

[
  {
     'Product':'Cabinet',
     'color' : { 'Blue','Yellow' }
  },
  {
     'Product':'CounterTop',
     'color' : { 'White' }
  }
]

我寫了一個代碼來存檔它,但我沒有得到預期的結果。

 build.forEach(pr => { if (pr.Product in result) { result[pr['Product']]['Color'] = pr['Color']; } else { result[pr['Product']] = { 'Product': pr['Product'], 'Color': pr['Color'] } } });

以上代碼返回

 [
  {
     'Product':'Cabinet',
     'color' : 'Yellow' 
  },
  {
     'Product':'CounterTop',
     'color' : 'White'
  }
]

在您的 output 中期望'color': { 'Blue','Yellow' }是錯誤的。 對象是數據的鍵值對。

相反,您希望color是一個數組。 我調整了你的代碼:

build.forEach(pr => {
  if (pr.Product in result) {
      result[pr['Product']]['Color'].push(pr['Color']);
  } else {
      result[pr['Product']] = {
          'Product': pr['Product'],
          'Color': [pr['Color']]
      }
  }
});

現在考慮如何防止數組中出現重復值。 @Lissy93 的回答通過使用findIndex來幫助解決這個問題。

這是一個工作版本。 希望能幫助到你:)

 const builds = [ { 'Product': 'Cab.nets', 'Color': 'Blue' }, { 'Product': 'CounterTop', 'Color': 'White' }, { 'Product': 'Cab.nets', 'Color': 'Yellow' }, { 'Product': 'Cab.nets', 'Color': 'Yellow' } ]; const results = []; builds.forEach((build) => { const index = results.findIndex((b) => b.Product === build.Product); if (index === -1) { results.push({Product: build.Product, Color: [ build.Color ]}); } else { results[index] = {Product: build.Product, Color: [...results[index].Color, build.Color ]} } }); console.log(results);

您代碼中的主要問題是您混淆了 arrays 和color的鍵值對。 KVP 看起來像{ color: 'red' } ,而 arrays 將是: [ 'red', 'blue']

使用此策略:

  • 尋找獨特的產品
  • 基於獨特的產品使用Array#mapArray#filter構建所需的數據

請參閱下面的演示:

 const builds = [ { 'Product': 'Cab.nets', 'Color': 'Blue' }, { 'Product': 'CounterTop', 'Color': 'White' }, { 'Product': 'Cab.nets', 'Color': 'Yellow' }, { 'Product': 'Cab.nets', 'Color': 'Yellow' } ], output = [...new Set(builds.map(({Product}) => Product))].map(Product => ({ Product, Color:builds.filter(({Product:P}) => P === Product).map(({Color}) => Color) }) ); console.log(output);

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM