You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何在同一对象内移动数组数据?将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 its cards array includes card1 (using some() for a quick check).
  • Get current index: findIndex() gives us where card1 is currently located in the cards array.
  • Remove and reinsert:
    • splice(cardCurrentIndex, 1) pulls card1 out of its current spot and returns it.
    • splice(1, 0, card1) inserts card1 at index 1 (the second position), shifting any existing card at that index to the right.
  • Optional label update: If your label field 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

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.15 06:35:57