简体   繁体   中英

How to create new array with conditionally adding an additional property comparing two arrays

I have two arrays

lockers: [
  {
    locker_id: 1,
    label: {
      size: 1,
      label: "large"
    }
  },
  {
    locker_id: 2,
    label: {
      size: 3,
      label: "large"
    }
  },
  {
    locker_id: 3,
    label: {
      size: 3,
      label: "large"
    }
  }
]

and

selectedLockers: [1, 2]

Now I need to create a new array by conditionally matching lockers.id === selectedLocker[id] and if they match add a new property color:"yellow" if does not match color:"red"

What I Actually want is:

newLockers: [
  {
    locker_id: 1,
    label: {
      size: 1,
      label: "large",
      color: "yellow"
    }
  },
  {
    locker_id: 2,
    label: {
      size: 3,
      label: "large",
      color: "yellow"
    }
  },
  {
    locker_id: 3,
    label: {
      size: 3,
      label: "large",
      color: "red"
    }
  }
]

You can do it this way.

 const lockers = [ { locker_id:1,label:{ size:1,label:"large" } }, { locker_id:2,label:{ size:3,label:"large" } }, { locker_id:3,label:{ size:3,label:"large" } } ]; const selectedLockers = [1,2] const newArray = lockers.map((locker) => { if (selectedLockers.includes(locker.locker_id)) { locker.label.color = "yellow" } else { locker.label.color = "red" } return locker; })

I would create a set for lookup:

 s = new Set(selectedLockers)

then just map over your data:

 lockers.map(e => {
   e.label.color = s.has(e.locker_id) ? 'yellow' : 'red';
   return e;
 } )
  

You can loop over your lockers array and for each element check whether that id is present in selectedLockers array. if yes then add the color yellow else red.

let newLockers = lockers.map(ele => {
    if (selectedLockers.includes(ele.locker_id)) {
       ele.color = "yellow";  
    } else {
       ele.color = "red";
    }
    return ele;
});
lockers.map((locker) =>
    selectedLockers.includes(locker.locker_id)
      ? { ...locker, label: { ...locker.label, color: 'yellow' } }
      : { ...locker, label: { ...locker.label, color: 'red' } })

Map over the lockers array to see if its id present in the selectedLockers array using includes method.

 let lockers = [{ locker_id: 1, label: { size: 1, label: "large" } }, { locker_id: 2, label: { size: 3, label: "large" } }, { locker_id: 3, label: { size: 3, label: "large" } } ]; let selectedLockers = [1, 2]; const result = lockers.map((locker) => { let { label,locker_id } = locker; selectedLockers.includes(locker_id)? (label.color = "yellow"): (label.color = "red"); return locker; }); console.log(result);

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