简体   繁体   中英

Iterate over an array of object and change object value

I'm trying to iterate over an array of objects that looks like this:

const arr = [{
  id: 1,
  name: "John",
  storeName: "Amazon",
  price: 100,
  isRecieved: false,
  deliveryDate: some date
}, ....]

I'm iterating over the array with product ID that I received from the user, finding the relevant item according to it's id and changing the key "isRecieved" from false to true.

This is my code:

const filterReceivedProduct = (list, id) => {
  const changeReceivedState = list.filter((item) => {
      return item.id === id ? **item[isRecieved]** = true : item;
  })
  return changeReceivedState
}

But when I'm trying to access the object using bracket notation it return the value (in this case 'false') and I can't change the value to true..

What I'm doing wrong?

You don't need to use .filter() here. The filter method is for removing elements from an array. What you want to do is map each element/object to a new object, which has all the properties from the old object, containing an updated isRecieved property. To create a new object with all the properties of the old object, you can spread the properties and values from the old object into a new one ( {...item} ). You can then update the isRecived based on your whether the item id matched the id passed into your function:

 const arr = [{ id: 1, name: "John", storeName: "Amazon", price: 100, isRecieved: false, deliveryDate: 'some date' }, { id: 2, name: "Alex", storeName: "Apple", price: 200, isRecieved: false, deliveryDate: 'some date2' }]; const filterReceivedProduct = (list, id) => list.map(item => ({...item, isRecieved: item.id === id // sets isRecieved to true or false based on the equalty comparison })); const res = filterReceivedProduct(arr, 1); console.log(res);

By creating a new object within the .map() callback, you're never mutating the original objects in your arr , treating everything as immutable.

Here filter make no sense. Filter use to filter some array based on condition. If you just want to change some property of an object inside array then use map for this purpose.

See below example.

 const arr = [{ id: 1, name: "John", storeName: "Amazon", price: 100, isRecieved: false, deliveryDate: 'some date' }, { id: 2, name: "Doe", storeName: "Amazon", price: 100, isRecieved: false, deliveryDate: 'some date' }]; filterReceivedProduct = (list, id) => { return list.map(item => { if(item.id === id) { item.isRecieved = true; } return item; }); } console.log(filterReceivedProduct(arr, 1))

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM