在 javascript 中将值从一个对象数组转移到另一个对象数组

问题描述 投票:0回答:1

我有一个对象数组。这些对象有一个属性,它也是一个数组。我想将一个新值插入到我的对象数组中。它必须是连续的,因为我总是想将值添加到第一个对象数组中,但如果第一个对象数组中已经有一个项目,那么我想将其移动到第二个对象数组中以便为新项目腾出空间。

Diagram

我得到的结果是前两个对象具有列表中的最新值,最后一个对象具有第一个添加值。预期结果是数组中的第一个对象具有值为“item2”的列表,数组中的下一个对象具有值为“item1”的列表,最后一个对象具有空列表,直到我添加另一个项目。

谢谢您的帮助。

function addItem(arr, item) {
  let current = 0;
 
  //if first object list is empty add the item 
  if(!arr[0].list.length){
    arr[current].list.push(item);
    return
  }

  while (current < arr.length) {
    
    //check the current objects list is not empty
    if(arr[current].list.length != 0){
      //check if there is a next object in the array and it has an item in it's list
      if(arr[current + 1] && !arr[current + 1].list.length){
        //if there is a next object and it does not have an item in it's list
        //remove the current item in current list
        let move_item = arr[current].list.shift();
        //add the item to the next object in the array
        arr[current + 1].list.push(move_item);
        //add the new item to the current object in the array
        arr[current].list.push(item);   
      }
    }
    console.log(arr[current]);
    current++; 
  }
}

// Example usage
let item = 'item1';
let item2 = 'item2';
const myArr = [
  {name:'one', list:[]},
  {name:'two', list:[]},
  {name:'three', list:[]}
];
addItem(myArr, item);
addItem(myArr, item2);
javascript arrays object oop
1个回答
0
投票

您可以从末尾开始迭代,并将所有项目移动到数组的末尾。

function addItem(arr, item) {
    let current = arr.length;
    while (--current) {
        if (arr[current - 1].list.length) arr[current].list.push(arr[current - 1].list.shift());
    }
    arr[0].list.push(item);
}

const
    myArr = [{ name: 'one', list: [] }, { name: 'two', list: [] }, { name: 'three', list: [] }];
    
console.log(JSON.stringify(myArr));
addItem(myArr, 'item1');
console.log(JSON.stringify(myArr));
addItem(myArr, 'item2');
console.log(JSON.stringify(myArr));
addItem(myArr, 'item3');
console.log(JSON.stringify(myArr));
addItem(myArr, 'item4');
console.log(JSON.stringify(myArr));

© www.soinside.com 2019 - 2024. All rights reserved.