Как удалить элемент с одного объекта и переместить его на другой? - PullRequest
2 голосов
/ 03 августа 2020

Итак, у меня есть этот массив

const array = [{
    id: 1,
    items: {
      '1': {
        name: 'apple',
        id: '1',
        parent: {
          id: 1
        }
      },
      '2': {
        name: 'orange',
        id: '2',
        parent: {
          id: 2
        }
      },
    }
  },
  {
    id: 2,
    items: {
      '3': {
        name: 'banana',
        id: '3',
        parent: {
          id: 3
        }
      },
    }
  },
]

Я хочу переместить любой элемент из одного items подобъекта в другой.

Пока что я выясняю, как удалить элемент из исходного объекта и обновляя этот элемент данными о новом «родителе».

const moveObjects = (element, itemId) => {
      const newElements = array.map(el => {
        const elsIds = Object.keys(el.items);
    
    
        elsIds.forEach(id => {
          if (id == itemId) {
            const tempItem = el.items[itemId];
            tempItem.parent = {
              id: element.id,
            };
            delete el.items[itemId];
          }
        });
        return el;
      });
    
      return newElements;
    }

const elementToMoveTo = {
  id: 2,
  ...
}

console.log(moveObjects(elementToMoveTo, 1))

И прямо сейчас я борюсь с тем, как обновить целевой объект с помощью этого tempItem. Возможно, для этого нужен другой подход.

Любая помощь будет принята с благодарностью. Ссылка на jsfiddle

Результат из приведенного выше кода должен быть

const array = [{
    id: 1,
    items: {
      '2': {
        name: 'orange',
        id: '2',
        parent: {
          id: 2
        }
      },
    }
  },
  {
    id: 2,
    items: {

      '1': {
        name: 'apple',
        id: '1',
        parent: {
          id: 2
        }
      },
      '3': {
        name: 'banana',
        id: '3',
        parent: {
          id: 3
        }
      },
    }
  },
]

Ответы [ 3 ]

0 голосов
/ 03 августа 2020

Это работает! Я пробовал и проверял. Не путайте с &&, это в основном просто для проверки, является ли предыдущее значение null / undefined (в основном любое значение, которое возвращает ложное значение)

    let theItemKey = "3";
    let fromObj = 1;
    let toObj = 0;
    let theItem = array && 
                    array[fromObj] && 
                      array[fromObj].items && 
                        array[fromObj].items[theItemKey];
    array[toObj].items[theItemKey] = theItem;
    delete array[fromObj].items[theItemKey];
0 голосов
/ 03 августа 2020

На вашем месте я бы написал такой код:

const array = [{
    id: 1,
    items: {
      '1': {
        name: 'apple',
        id: '1',
        parent: {
          id: 1
        }
      },
      '2': {
        name: 'orange',
        id: '2',
        parent: {
          id: 2
        }
      },
    }
  },
  {
    id: 2,
    items: {
      '3': {
        name: 'banana',
        id: '3',
        parent: {
          id: 3
        }
      },
    }
  },
]


const moveObjects = (elementId, itemId) => {

  //creates a new array from existed one
  let newArray = [...array];

  //finds an element where I should move the item
  let element = newArray.find(el => el.id === elementId);
  let item = null;

  //if element is found -> continue
  if (element) {
  
    newArray.forEach(el => {
    
      //if the item is a property of an element.items -> copies the founded item to the variable "item" then delete the property from the previous parent 

      if (el.items[itemId]) {
        el.items[itemId].parent.id = itemId;
        item = el.items[itemId];

        delete el.items[itemId];
      }
    });
    
    //adds item to a new parent
    element.items[itemId] = item;
  }

  //returns a new array 
  return newArray;
}

console.log(moveObjects(2, "1"))
0 голосов
/ 03 августа 2020

Вы можете попробовать что-то вроде этого:

function move(arr, fromId, toId, itemToMoveId) {
  
  let fromElem = null;
  let toElem = null;
  
  arr.forEach(elem => {
      if (elem.id === fromId) fromElem = elem;
      if (elem.id === toId) toElem = elem;
  });   
  
  let itemToMove = fromElem.items[itemToMoveId];
  
  delete fromElem.items[itemToMoveId];
  
  toElem.items[itemToMoveId] = itemToMove;
 
}

// move item['1'] from object with id 1 to object with id 2
move(array, 1, 2, '1');

Этот код прост и может не охватывать все случаи (проверки на null, что угодно). Он изменяет входной массив, но вы можете изменить функцию, чтобы вместо этого возвращалось что-то новое.

Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...