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 update the existing list value for specific key in NodeJS

I’ve wanted to update the specific key’s value dynamically in NodeJS. Initially, this key USER_SAL has the value of 0, I would like to update this key USER_SAL value dynamically from USER_SAL -> 0 To USER_SAL -> 50000. Please find my code below:

const obj = {
    users: [{
        name: "USER_ID",
        value: "ASD32343D",
      },
      {
        name: "USER_NAME",
        value: "mark",
      },
      {
        name: "USER_ALT_ID",
        value: "DSDF3234",
      },
      {
        name: "USER_LOC",
        value: "NY",
      },
      {
        name: "USER_SAL",
        value: "0",
      },
    ],
  };
  const changes = {
    USER_ALT_ID: "myuser.altID", // changing to different key name
    USER_LOC: "myuser.loc", // changing to different key name
  };
  
  obj.users.forEach((o) => {
    if (changes[o.name]) o.name = changes[o.name];
  });
  
  console.log(obj.users);

Expected output:

[
  { name: 'USER_ID', value: 'ASD32343D' },
  { name: 'USER_NAME', value: 'mark' },
  { name: 'myuser.altID', value: 'DSDF3234' },
  { name: 'myuser.loc', value: 'NY' },
  { name: 'USER_SAL', value: '50000' }
]

I’m not very good at NodesJS, can someone please help how can we update the specific key’s value. Appreciate your help in advance. Thanks!

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

>Solution :

Use map instead of forEach, map allows you to create a new array based on changes to an old one. See below:

const obj = {
    users: [{
        name: "USER_ID",
        value: "ASD32343D",
      },
      {
        name: "USER_NAME",
        value: "mark",
      },
      {
        name: "USER_ALT_ID",
        value: "DSDF3234",
      },
      {
        name: "USER_LOC",
        value: "NY",
      },
      {
        name: "USER_SAL",
        value: "0",
      },
    ],
  };
  const changes = {
    USER_ALT_ID: "myuser.altID", // changing to different key name
    USER_LOC: "myuser.loc", // changing to different key name
  };
  
  const newUsers = obj.users.map((o) => {
    if (changes[o.name]) o.name = changes[o.name];
    if(o.name === "USER_SAL") o.value = "50000";
    return o;
  });
  
  obj.users = newUsers;
  
  console.log(obj.users);
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