Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Update Array of Objects based on Array of strings

I am trying to update an array of objects. The active key will be set to true based on user’s selection or the array of strings.

For an instance, on selecting ABC, DEF, the active key will be set to true for these two Ids.

const defaultArray = [
  {
    "active": true,
    "id": 1,
    "name": "ABC",
    "value": "1"
  },
  {
    "active": true,
    "id": 2,
    "name": "DEF",
    "value": "2"
  },
  {
    "active": true,
    "id": 3,
    "name": "GHI",
    "value": "3"
  }
]
const selectedArray = [
  "ABC",
  "DEF"
]

So now I need to create a new Array based on the default array and assign active=true only for array of string in selecetedArray.

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

Result will look like

const newArray = [
  {
    "active": true,
    "id": 1,
    "name": "ABC",
    "value": "1"
  },
  {
    "active": true,
    "id": 2,
    "name": "DEF",
    "value": "2"
  },
  {
    "active": false,
    "id": 3,
    "name": "GHI",
    "value": "3"
  }
]

I tried.

const arrCopy = [...defaultArray]
arrCopy.forEach(x => x.active = false)
arrCopy.forEach(x => {
    if(selectedArray.includes(x.name))
        x.active =  true
})

console.log(arrCopy)

The above code works, but is there any more standard way to achieve the same. thanks

>Solution :

You don’t need two loops to achieve that, you can directly use map method on the defaultArray.

defaultArray.map(x => ({...x, active: selectedArray.includes(x.name)}))
const defaultArray = [
  {
    "active": true,
    "id": 1,
    "name": "ABC",
    "value": "1"
  },
  {
    "active": true,
    "id": 2,
    "name": "DEF",
    "value": "2"
  },
  {
    "active": true,
    "id": 3,
    "name": "GHI",
    "value": "3"
  }
]
const selectedArray = [
  "ABC",
  "DEF"
]

const newArray = defaultArray.map(x => ({...x, active: selectedArray.includes(x.name)}))

console.log(newArray)
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading