簡體   English   中英

根據鍵對對象數組進行分組並返回新的對象數組

[英]Group array of objects based on a key and return the new array of objects

我有下面的對象數組,我想根據實體名稱對其進行分組,並且我查看了兩個對象是否具有相同的實體名稱,如果是,那么我必須查看顏色,如果兩個對象的顏色相同,那么我必須查看將它們合二為一,並結合兩者的細節。

如果兩個對象的實體名稱相同且顏色不同,那么我必須將它們分組並將顏色設置為黃色,並且必須組合細節並返回新的對象數組。

let data = [
    {entityName: "Amazon", color: "red", details: "Hello"}
    {entityName: "Amazon", color: "green", details: "World"}
    {entityName: "Flipkart", color: "green", details: "1234567"} 
]

我上面數組的例外輸出應該是這個。

result = [
    {entityName: "Amazon", color: "yellow", details: "Hello world"}
    {entityName: "Flipkart", color: "green", details: "1234567"} 
]

誰能告訴我我該怎么做

您可以遍歷項目並找到匹配的項目並實現您的邏輯。

 let data = [{ entityName: "Amazon", color: "red", details: "Hello" }, { entityName: "Amazon", color: "green", details: "World" }, { entityName: "Flipkart", color: "green", details: "1234567" } ]; var result = []; for (const value of data) { const item = result.find(f => f.entityName === value.entityName); if (!item) { result.push(value); } else { if (item.color !== value.color) { item.color = 'yellow'; } item.details += ' ' + value.details; } } console.log(result);

您可以遍歷數據並搜索具有相同名稱但顏色不同的項目的索引(if 語句檢查 indexOfFound >= 0,因為如果未找到項目,則findIndex返回 -1)對項目進行變異,然后刪除找到的項目。

所以像這樣:

 let data = [{ entityName: "Amazon", color: "red", details: "Hello" }, { entityName: "Amazon", color: "green", details: "World" }, { entityName: "Flipkart", color: "green", details: "1234567" }]; data.forEach(item => { const indexOfFound = data.findIndex(diffItem => diffItem.entityName == item.entityName && diffItem.color !== item.color); if (indexOfFound >= 0) { item.color = "yellow"; item.details = `${item.details} ${data[indexOfFound].details.toLowerCase()}` data.splice(indexOfFound, 1); } }); console.log(data);

暫無
暫無

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

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