![](/img/trans.png)
[英]Remove the specific object from array and shift this object on 0 index of the same array
[英]How can I remove a specific index from an array and then insert a new one on that same index?
我正在嘗試做一件事,但我有 2 個選擇
我有這段代碼:
const handleClick = () => {
for (let i = 0; i < qs.length; i++) {
if (qs[i].id === getNewQ.id) {
const qsCopy = [...qs].filter((q) => q.id !== getNewQ.id);
return [...qsCopy, { ...newGroup }];
}
}
return [...qs];
};
它從數組中刪除該項目,但是當它添加新項目時,它會將其添加到最后一個索引中。 但我需要的是,將這個新項目添加到刪除另一個項目的索引中。
清楚嗎?
我創建了一個可重現的示例: https://codesandbox.io/s/pedantic-darwin-4tty0?file=/src/App.tsx:912-1171
在示例中,您會注意到新項目是如何添加到最后一個索引的。 它需要盡可能通用,因為它是動態的。 並非所有時間都是相同的索引。
Map qs
代替,當 ID 匹配時,返回newGroup
代替 state 中的前一項:
const handleClick = () => qs.map((q) => (
q.id === getNewQ.id
? { ...newGroup }
: q
));
為了避免遍歷整個數組,使用 findIndex 如下
const handleClick = () => {
const qsCopy = [...qs];
const itemIndex = qs.findIndex(({ id }) => (id === getNewQ.id));
if (itemIndex !== -1) {
qsCopy[itemIndex] = { ...newGroup };
}
return qsCopy;
};
CertainPerformance 提供了一個很好的解決方案,允許您只對數組進行一次 foreach。
僅作為信息可能對其他人有用:
還有其他方法可以做到這一點你可以找到你的 object 然后添加你的屬性。 https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/find喜歡:
const myObject = qs.find(q => q.id === myId)
但是傳播是行不通的,因為它會創建另一個 object。
另一種可能性:如果需要,一個 findIndex 和一個拼接
https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/splice https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects /數組/查找索引
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.