如果可能的話,我在 ES6 中尋找這種邏輯,將 2 個陣列元素組合到單個陣列中。
以下是來自后端的資料。
dataFromBackend = [
{
animal: 'Elephant',
height: 123,
weight: 456
},
{
animal: 'Elephant',
food: 'abc',
sleep: 'xyz'
},
{
animal: 'Tiger',
height: 123,
weight: 456
},
{
animal: 'Tiger',
food: 'abc',
sleep: 'xyz'
},
{
animal: 'Rabbit',
height: 123,
weight: 456
}
]
預期產出
convertedData = [
{
animal: 'Elephant',
height: 123,
weight: 456,
food: 'abc',
sleep: 'xyz'
},
{
animal: 'Tiger',
height: 123,
weight: 456,
food: 'abc',
sleep: 'xyz'
},
{
animal: 'Rabbit',
height: 123,
weight: 456,
food: 'No Data',
sleep: 'No Data'
}
]
如果某些屬性沒有資料,我必須插入“無資料”
uj5u.com熱心網友回復:
我將創建一個函式,您可以通過該函式通過提供資料和道具來合并 obj。No Data是不好的做法,使用鍵的存在來確定 obj 在該鍵上是否具有值(也就是如果沒有鍵food,則該鍵上沒有資料。
dataFromBackend = [
{ animal: 'Elephant', height: 123, weight: 456 },
{ animal: 'Elephant', food: 'abc', sleep: 'xyz' },
{ animal: 'Tiger', height: 123, weight: 456 },
{ animal: 'Tiger', food: 'abc', sleep: 'xyz' },
{ animal: 'Rabbit', height: 123, weight: 456 },
];
// prop to merge by (string), arr of objects (any: [])
function mergeByProp(prop, arr) {
let returnArr = [];
for (let obj of arr) {
if (returnArr.some((target) => target[prop] === obj[prop])) {
let target = returnArr.find((find) => find[prop] === obj[prop]);
Object.assign(target, { ...target, ...obj });
} else {
returnArr.push(obj);
}
}
console.log(returnArr);
}
this.mergeByProp('animal', this.dataFromBackend);
uj5u.com熱心網友回復:
首先,我會使用reduce 方法按animal屬性對元素進行分組,然后再次遍歷它們以分配缺少的屬性'No Data':
dataFromBackend = [
{ animal: 'Elephant', height: 123, weight: 456 },
{ animal: 'Elephant', food: 'abc', sleep: 'xyz' },
{ animal: 'Tiger', height: 123, weight: 456 },
{ animal: 'Tiger', food: 'abc', sleep: 'xyz' },
{ animal: 'Rabbit', height: 123, weight: 456 }
];
let rawResult = dataFromBackend .reduce((acc, element) => {
if (!acc[element.animal]) {
acc[element.animal] = element
}
acc[element.animal] = { ...acc[element.animal], ...element }
return acc;
}, {});
let convertedData = Object.values(rawResult).map(r => ({
...r,
food: r.food ?? 'No Data',
sleep: r.sleep ?? 'No Data'
}));
console.log(convertedData);
uj5u.com熱心網友回復:
我會構建一個字典并按名稱對所有動物進行分組,然后將它們與擴展運算子合并
type Animal = {
animal: string;
height?: number | string;
weight?: number | string;
food?: string;
sleep?: string;
};
@Component({
selector: 'app-one',
templateUrl: './one.component.html',
styleUrls: ['./one.component.scss'],
})
export class OneComponent {
dataFromBackend: Animal[] = [
{ animal: 'Elephant', height: 123, weight: 456 },
{ animal: 'Elephant', food: 'abc', sleep: 'xyz' },
{ animal: 'Tiger', height: 123, weight: 456 },
{ animal: 'Tiger', food: 'abc', sleep: 'xyz' },
{ animal: 'Rabbit', height: 123, weight: 456 },
];
convertedData: Animal[] = [];
ngOnInit() {
const animalDict: { [key: string]: Animal[] } = {};
for (const el of this.dataFromBackend) {
if (!animalDict[el.animal]) animalDict[el.animal] = [];
animalDict[el.animal].push(el);
}
for (const animalName of Object.keys(animalDict)) {
let animal: Animal = {
animal: animalName,
height: 'No Data',
weight: 'No Data',
food: 'No Data',
sleep: 'No Data',
};
for (const entry of animalDict[animalName]) {
animal = { ...animal, ...entry };
}
this.convertedData.push(animal);
}
}
}
Stackblitz:https ://stackblitz.com/edit/angular-ivy-chvdcw?file=src/app/app.component.ts
uj5u.com熱心網友回復:
使用 reduce 合并具有相同animal名稱的陣列資料。
Object.values將物件轉換為陣列
更多關于減少
const dataFromBackend = [
{ animal: 'Elephant', height: 123, weight: 456 },
{ animal: 'Elephant', food: 'abc', sleep: 'xyz' },
{ animal: 'Tiger', height: 123, weight: 456 },
{ animal: 'Tiger', food: 'abc', sleep: 'xyz' },
{ animal: 'Rabbit', height: 123, weight: 456 },
];
let mergedData = Object.values(
dataFromBackend.reduce((acc, data) => {
data.food = data.food || 'No Data';
data.sleep = data.sleep || 'No Data';
if (!acc[data.animal]) {
acc[data.animal] = data;
}
acc[data.animal] = { ...acc[data.animal], ...data };
return acc;
}, {})
);
console.log(mergedData);
uj5u.com熱心網友回復:
在這里,您有一個示例,說明如何處理 dataFromBackend 陣列以及如何生成包含元素的結果陣列作為具有相同動物屬性值的物件的合并:
//your input array (just with compact formatting for easier readying)
dataFromBackend = [
{ animal: 'Elephant', height: 123, weight: 456 },
{ animal: 'Elephant', food: 'abc', sleep: 'xyz' },
{ animal: 'Tiger', height: 123, weight: 456 },
{ animal: 'Tiger', food: 'abc', sleep: 'xyz' },
{ animal: 'Rabbit', height: 123, weight: 456 }
]
expectedAnimalProperties = ['animal','height','weight','food','sleep'];
//the map will be a temporary object
var map = {};
//for each element in the input array
dataFromBackend.forEach( (o, i) => {
//if there's yet no animal in map like o.animal
if(typeof map[o.animal] === 'undefined')
//init the animal inside the map
map[o.animal] = o;
//else if the animal already existed in the map
else
//integrate the properties of the object stored in map
map[o.animal] = {...map[o.animal], ...o};
});
//print the map to console
console.log(map);
//the result array
var result = [];
//for each key in map
Object.keys(map).forEach((k) => {
//push the merged animal in the result array
result.push( map[k] );
});
//print the result array
console.log(result);
//for each animal (merged) in result
result.forEach((oAnimal, iAnimal) => {
//for each properties expected from an animal object
expectedAnimalProperties.forEach((oExpectedKey, iExpectedKey) => {
//if that property isn't included in the current animal
if( !Object.keys(oAnimal).includes(oExpectedKey) ){
//add that property to the current animal with no data
oAnimal[oExpectedKey] = 'No Data';
}
});
});
//print the result array
console.log(result);
轉載請註明出處,本文鏈接:https://www.uj5u.com/gongcheng/457435.html
標籤:javascript 有角度的 打字稿
上一篇:當最后一個標記是可選的時,如何在正則運算式中捕獲除最后一個標記之外的所有標記
下一篇:如何在JS中構造輸入引數到物件
