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

How to modify the value of only one of the keyvalues in the json array of js and keep the others?

This is the data that needs to be processed

let test=[
  {
    "id": 28620,
    "name": "fenbi1",
    "dn": "chl"
  },
  {
    "id": 5941,
    "name": "fenbi2",
    "dn": "chl"
  },
  {
    "id": 5226,
    "name": "fenbi3",
    "dn": "chl"
  }]

The requirement is to change only dn to ch
the changed value is

  let test=[
  {
    "id": 28620,
    "name": "fenbi1",
    "dn": "ch"
  },
  {
    "id": 5941,
    "name": "fenbi2",
    "dn": "ch"
  },
  {
    "id": 5226,
    "name": "fenbi3",
    "dn": "ch"
  }]

This is the method I used

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

  test=test.map((item)=>({
    'id':item.id,
    'name':item.name,
    'dn':'ch'
  }))

This approach works but is not elegant because just to change one value you have to
write the others as well, is there a better way to implement this?

>Solution :

Just a simple for loop might be better than map in this situation

let test=[
  {
    "id": 28620,
    "name": "fenbi1",
    "dn": "chl"
  },
  {
    "id": 5941,
    "name": "fenbi2",
    "dn": "chl"
  },
  {
    "id": 5226,
    "name": "fenbi3",
    "dn": "chl"
  }]

  for (let item of test) {
     item.dn = 'ch'
  }

  console.log(test)
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