我想在物件陣列中添加一個條件物件。如果不滿足條件,我希望它就好像那個物件根本不存在一樣,同時保持其他物件的原樣。 考慮以下:
const CardBuildingBlock: FC = () => {
const type = 'typeA';
const typesOfCards = [
{name: 'Card A'
size: 'Medium'
action: 'make'},
{name: 'Card B'
size: 'Small'
action: 'break'},
{name: 'Card C'
size: 'Large'
action: 'build'},
//我嘗試執行以下操作,但不起作用
type == 'typeA' ? null : {
name: 'Card A'
size: 'Medium'
action: 'make'},
];
return(
typeOfCards.map(({name, size, action}) => (
<BuildCard
name = {name}
size = {size}
action = {action}
/>
)
)};
請幫忙。!!!
謝謝您的幫助。
uj5u.com熱心網友回復:
據我了解,您想在給定條件的情況下過濾掉陣列的所有元素。我要做的是向物件添加一個新鍵,指定是否應該顯示它,然后過濾和映射。
const typesOfCards = [
{ name: "Card A", size: "Medium", action: "make", type: "typeA" },
...
];
return typesOfCards.filter(card => card.type === "typeA").map(({ name, size, action }) => (
<BuildCard name={name} size={size} action={action} />
));
uj5u.com熱心網友回復:
在這種情況下,推送可能會很有用:
type === 'typeA' && typesOfCards.push({
name: 'Card A'
size: 'Medium'
action: 'make'}
)
也許你可能想把它包含在一個函式中,它應該回傳 typesOfCards 陣列
uj5u.com熱心網友回復:
這里最簡單的方法是Concat的新元素的陣列。如果條件為真,您將連接新元素。考慮這個例子:
// using if statement
const type = "typeA";
let additionalCardOfTypeA = {
name: "Card A",
size: "Medium",
action: "make",
};
let typesOfCards = [
{ name: "Card A", size: "Medium", action: "make" },
{ name: "Card B", size: "Small", action: "break" },
{ name: "Card C", size: "Large", action: "build" },
];
if (type === "typeA") {
typesOfCards = typesOfCards.concat(additionalCardOfTypeA);
}
// using ternary operator
const type = "typeA";
let additionalCardOfTypeA = {
name: "Card A",
size: "Medium",
action: "make",
};
let typesOfCards = [
{ name: "Card A", size: "Medium", action: "make" },
{ name: "Card B", size: "Small", action: "break" },
{ name: "Card C", size: "Large", action: "build" },
].concat(
type === "typeA"
? additionalCardOfTypeA
: []
);
編輯
要在特定位置插入新元素,您必須創建額外的陣列。首先,為您的元素找到一個位置。然后,創建一個包含原始索引之前所有內容的陣列,以及包含從索引到結尾的所有內容的陣列。然后將開始、新元素和結束連接到最終陣列中。
const type = "typeA";
let additionalCardOfTypeA = {
name: "Card A",
size: "Medium",
action: "make",
};
let typesOfCards = [
{ name: "Card A", size: "Medium", action: "make" },
{ name: "Card B", size: "Small", action: "break" },
{ name: "Card C", size: "Large", action: "build" },
];
if (type === "typeA") {
let indexForNewElement = getSomehowIndex();
// Getting everything before index
let head = typesOfCards.slice(0, indexForNewElement);
// Getting everything after index
let tail = typesOfCards.slice(indexForNewElement);
typesOfCards = head.concat(additionalCardOfTypeA).concat(tail);
}
轉載請註明出處,本文鏈接:https://www.uj5u.com/qiye/365180.html
標籤:javascript 反应 打字稿 下一个.js
上一篇:在vue方法中構造陣列
