如何在同一对象内移动数组数据?将card1移至cards数组第二位
How to Move
card1 to the Second Position in Its cards Array Got it, let's walk through how to shift card1 to the second spot in its parent cards array within your lanes structure. Here's a straightforward JavaScript solution tailored to your data:
Step-by-Step Implementation
First, let's start with your sample lanes data (I've added quotes around string IDs for valid syntax):
const lanes = [ { cards: [ { id: 'card1', title: 'Write a cool JS library', listId: "lane1" }, { id: 'card2', title: 'Make it generic enough', listId: "lane1" } ], id: "lane1", label: "2/2", title: "title.." }, { cards: [ { id: 'card3', title: 'Write README', listId: "lane2" } ], id: "lane2", label: "0/0", title: "Something title.." } ];
Now, here's the code to move card1:
// Locate the lane that contains card1 const targetLane = lanes.find(lane => lane.cards.some(card => card.id === 'card1')); if (targetLane) { // Find the current index of card1 in the cards array const cardCurrentIndex = targetLane.cards.findIndex(card => card.id === 'card1'); // Only run if card1 isn't already in the second position (index 1) if (cardCurrentIndex !== -1 && cardCurrentIndex !== 1) { // Remove card1 from its current position const [card1] = targetLane.cards.splice(cardCurrentIndex, 1); // Insert card1 at the second position (index 1) targetLane.cards.splice(1, 0, card1); // Optional: Update the lane's label if it depends on card order/count // targetLane.label = `${targetLane.cards.length}/${targetLane.cards.length}`; } } // Verify the result console.log(lanes[0].cards); // Output will be: // [ // { id: 'card2', title: 'Make it generic enough', listId: "lane1" }, // { id: 'card1', title: 'Write a cool JS library', listId: "lane1" } // ]
What Each Part Does
- Find the target lane:
lanes.find()checks each lane to see if itscardsarray includescard1(usingsome()for a quick check). - Get current index:
findIndex()gives us wherecard1is currently located in thecardsarray. - Remove and reinsert:
splice(cardCurrentIndex, 1)pullscard1out of its current spot and returns it.splice(1, 0, card1)insertscard1at index 1 (the second position), shifting any existing card at that index to the right.
- Optional label update: If your
labelfield is dynamic (like tracking completed cards), you can refresh it here to reflect any changes.
This solution works even if card1 moves to a different lane later—no hardcoding required!
内容的提问来源于stack exchange,提问作者Kaleem Elahi
相关产品推荐
相关产品推荐

