我正在學習Java腳本,并嘗試根據對象的特定屬性合并對象數組。
例如,我有以下數組,其中包含屬性a、b、c、pet和age的對象。如果兩個對象的屬性a、b、c相同,我想創建一個新陣列,將pet和年齡分組。如果a、b、c中的任何屬性不匹配,我想將它們作為新對象添加到輸出數組中。
myArray = [
{
a: 'animal',
b: 'white',
c: true,
pet: 'dog1',
age: 1
},
{
a: 'animal',
b: 'white',
c: true,
pet: 'dog2',
age: 2
},
{
a: 'animal2',
b: 'white',
c: true,
pet: 'cat1',
age: 5
},
{
a: 'animal2',
b: 'black',
c: false,
pet: 'cat2',
age: 1
}
]
按屬性a、b、c分組的輸出數組。我的輸出數組的第一個元素包含輸入數組中對象0,1的組合值,因為它們具有相同的a、b、c屬性。其余的作為單獨的值添加,因為它們在一個屬性中不同。
outputArray = [
{
a: 'animal',
b: 'white',
c: true,
pets: [{pet:'dog1,age:1},{pet:dog2,age:2}]
},
{
a: 'animal2',
b: 'white',
c: true,
pets: [{pet: 'cat1', age:5}]
},
{
a: 'animal2',
b: 'black',
c: false,
pets:[{pet: 'cat2', age: 1}]
}
]
最后我想要一個數組,所有元素按屬性a、b、c分組。有沒有有效的方法?我試著用for循環強制執行,但沒有成功。
TIA.
1) 您可以使用
Map
和for..of
輕松獲得結果2) 您還可以使用
Object.values
和reduce
實現samer結果