Home > OS >  JS - how to replace an object with spread operator AND condtion?
JS - how to replace an object with spread operator AND condtion?

Time:11-27

I have an array of objects. I need to:

  • check if the object has a specific key:value combination
  • if yes, replace a different value of this object
  • return both the objects

This is how I am trying to achieve it:

list.map(item => {
          return {
            ...item,
            ...(item["orderId"] === 'xyz' && { transactionNumber: 'sadfdas gasdgas' }),
          }

I also tried this condition instead:

...(orderId === 'xyz' && { transactionNumber: 'sadfdas gasdgas' })

and this:

...(item.orderId === 'xyz' && { transactionNumber: 'sadfdas gasdgas' })

and this:

...(item.orderId === 'xyz' ? { transactionNumber: 'sadfdas gasdgas' } : {})

However they all return the two objects in the list unchanged.

If I instead use this code:

.map(item => {
  return {
    ...item,
  transactionNumber: 'sadfdasgasdgas' 
  }
})

it replaces the transactionNumber for each object.

What am I doing wrong that the condition is not working?

Example of what should happen:

const list = [{
aaa: 123,
bbb: 222,
orderId: 555,
transactionNumber: 888
},
aaa: 123,
bbb: 222,
orderId: 555,
transactionNumber:999
]

If we process the variable above, the result would be:

[{
aaa: 123,
bbb: 222,
orderId: 555,
transactionNumber: 888
},
aaa: 123,
bbb: 222,
orderId: 555,
transactionNumber:999
]

But if we process the following array:

[{
aaa: 123,
bbb: 222,
orderId: "xyz",
transactionNumber: 888
},
aaa: 123,
bbb: 222,
orderId: 555,
transactionNumber:"sadfdasgasdgas"
]

the result should be:

[{
aaa: 123,
bbb: 222,
orderId: "xyz",
transactionNumber: 888
},
aaa: 123,
bbb: 222,
orderId: 555,
transactionNumber:999
]

CodePudding user response:

Either return an updated object if the condition matches, or return the object if it doesn't.

const list = [
  { name: 1, orderId: 'abc', transactionNumber: 1 },
  { name: 2, orderId: 'xyz', transactionNumber: 2 },
  { name: 3, orderId: 'efg', transactionNumber: 3 }
];

// Make a copy of the object "in transit"
const out = list.map(({ ...item }) => {

  // Update the number of the object if
  // the condition is true
  if (item.orderId === 'xyz') {
    item.transactionNumber = 'test';
  }
  
  // Return the item
  return item;

});

console.log(out);

CodePudding user response:

You can simply use a ternary operator as follows:

const list = [ { orderId: "xyz", transactionNumber: "1" }, { orderId: "abc", transactionNumber: "2" } ];

const res = list.map(item => ({
  ...item,
  transactionNumber: item["orderId"] === 'xyz' ? 'sadfdas gasdgas' : item["transactionNumber"]
}));

console.log(res);

  • Related