Home > Software design >  Change values in object without changing parent object
Change values in object without changing parent object

Time:12-12

I have a object with some (cards) values and I would like have another object which has values converted (cards by name) by another function.

cardsHand = [
{ value: "1", suit: "C" },
{ value: "13", suit: "C" },
{ value: "12", suit: "C" },
{ value: "11", suit: "C" },
{ value: "10", suit: "C" },
];

function sortCards(cardsHand) {
//SORT VALUES
let sortedCardsByValue = [];
sortedCardsByValue = cardsHand.sort(
(currCardA, currCardB) => currCardA.value - currCardB.value);

//CHANGE VALUES
let convertedCards = cardsHand;
convertedCards.forEach((element) => {
if ( element.value === 1) element.value = `A`;
if ( element.value === 11) element.value = `J`;
if ( element.value === 12) element.value = `Q`;
if ( element.value === 13) element.value = `K`;
});

return {
convertedCards,
sortedCardsByValue,
};
}

console.log(sortCards(cardsHand).convertedCards);
console.log(sortCards(cardsHand).sortedCardsByValue);

So I would like to achive object sortedCardsByValue:

[
{ value: '1', suit: 'C' },
{ value: '10', suit: 'C' },
{ value: '11', suit: 'C' },
{ value: '12', suit: 'C' },
{ value: '13', suit: 'C' }
]`

and object convertedCards (which is sorted like parent but with changed names for example 1->A; 11->J):

[
{ value: 'A', suit: 'C' },
{ value: '10', suit: 'C' },
{ value: 'J', suit: 'C' },
{ value: 'Q', suit: 'C' },
{ value: 'K', suit: 'C' }
]

But my code from the beginning creates both objects the same.

I have made some functions to solve this bug. I've tried map methos, replace method, forEach, Object.values().

CodePudding user response:

This let convertedCards = cardsHand; means - create a new variable with a reference to exactly the same object

This let sortedCardsByValue = []; does nothing because you assign a different array in the next line

Sort works in place so you don't have to assign to a new variable

const cardsHand = [{
    value: "1",
    suit: "C"
  },
  {
    value: "13",
    suit: "C"
  },
  {
    value: "12",
    suit: "C"
  },
  {
    value: "11",
    suit: "C"
  },
  {
    value: "10",
    suit: "C"
  },
];

function sortCards(cardsHand) {
  cardsHand.sort(
    (currCardA, currCardB) => currCardA.value - currCardB.value);

  let convertedCards = cardsHand.map(obj => ({ ...obj
  }));
  convertedCards.forEach((element) => {
    if ( element.value === 1) element.value = `A`;
    if ( element.value === 11) element.value = `J`;
    if ( element.value === 12) element.value = `Q`;
    if ( element.value === 13) element.value = `K`;
  });

  return {
    convertedCards,
    sortedCardsByValue: cardsHand,
  };
}

const {
  convertedCards,
  sortedCardsByValue,
} = sortCards(cardsHand)

console.log(convertedCards);
console.log(sortedCardsByValue);

  • Related