![](/img/trans.png)
[英]How can remove keys with empty values in an Object Array in TypeScript?
[英]How to conditionally change values of keys of an object in an object array in Typescript
我有以下 object ,它是名為objectArray
of ClossTypes clothesTypes[]
的數組中的鍵。
const objectArray: clothesTypes[] = [
{
trousers: 90,
'skirts and jackets': 47,
scarfs: 100,
},
]
然后我有另一個userData[]
類型的數組,它正在更新(當用戶購買布料時)。
const userArray: userData[] = [
{
name: 'David',
clothType: 'trousers',
price: 45,
},
{
name: 'Joanna',
clothType: 'scarfs',
price: 5,
},
{
name: 'Gillian',
clothType: 'trousers',
price: 35,
},
]
我需要做的是通過在 userArray 中獲取具有相關“clothType”屬性的對象數量來更新第一個objectArray
鍵的userArray
。 在這個例子中,褲子應該被指定為 2,“裙子和夾克”應該被指定為 0,圍巾應該被指定為 1。
objectArray.map(item => ({
...item,
...{
trousers: userArray.filter(d => d.clothType === 'trousers').length,
'skirts and jackets': userArray.filter(d => d.clothType === 'skirts and jackets').length,
scarfs: userArray.filter(d => d.clothType === 'scarfs').length,
},
})),
如何在不單獨為每個鍵分配值的情況下一次完成上述操作?
謝謝你
問題的作者指出objectArray
是一個長度始終為 1 的數組。考慮到這一點,這是我的建議 -
就像我在上面的評論中所說的那樣,沒有辦法“一次”完成所有操作,您將不得不迭代和計數,但您可以稍微改進算法(特別是,如果objectArray
不需要是數組,因為長度總是一)
鏈接到 TypeScript Playground 中的完整工作示例
const userArray: userData[] = [
{
name: 'David',
clothType: 'trousers',
price: 45,
},
{
name: 'Joanna',
clothType: 'scarfs',
price: 5,
},
{
name: 'Gillian',
clothType: 'trousers',
price: 35,
},
]
const clothesCount: clothesTypes = {
trousers: 90,
'skirts and jackets': 47,
scarfs: 100,
}
userArray.reduce((pv, cv) => {
switch(cv.clothType) {
case 'scarfs':
pv['scarfs'] += 1;
break;
case 'skirts and jackets':
pv['skirts and jackets'] += 1;
break;
case 'trousers':
pv['trousers'] += 1;
break;
}
return pv;
}, clothesCount)
如果該屬性存在於objectArray
中,您可以查看userArray
並添加計數。
const objectArray: clothesTypes[] = [{ trousers: 90, 'skirts and jackets': 47, scarfs: 100, }, ]; const userArray: userData[] = [{ name: 'David', clothType: 'trousers', price: 45, }, { name: 'Joanna', clothType: 'scarfs', price: 5, }, { name: 'Gillian', clothType: 'trousers', price: 35, }, ]; const objectArrayClone = [...objectArray]; const objectArrayV = objectArrayClone[0]; userArray.forEach((obj) => { const { clothType } = obj; if (clothType in objectArrayV) { objectArrayV[clothType]++; } }); console.log(objectArrayClone);
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.