add new value to JSON files

Issue

Can you tell me how to add new value to JSON files, if it can be taken from this file?
I have a lot of JSON files and they are missing one value ("id:"). The good news is that these files have the value "name:" which contains text and numbers. I could use these numbers as the "id:" (file names are also numeric and I can use the file name for the value "id:"). Here’s an example of how it is

{
    ...,
    "name": "abcd #109956",
    ...,
  }

and how I need to get results

{
    ...,
    "id": 109956,
    "name": "abcd #109956",
    ...,
  }

P.S.
I can merge all these files into one JSON. If it’s easier to do it with one file and add a new value everywhere, tell me how to do it
Thank you!

Solution

If you just want to add id to your JSON objects you can do it as follows. (If you can take all those objects into one array.)

const arr = [
  {
    name: "abcd #109956",
  },
  {
    name: "abc #109957",
  },
  {
    name: "abc #109958",
  },
];

arr.forEach((element) => {
  element.id = parseInt(element.name.split("#")[1]);
});

console.log(arr);

OUTPUT

[
  { name: 'abcd #109956', id: 109956 },
  { name: 'abc #109957', id: 109957 },
  { name: 'abc #109958', id: 109958 }
]

Hope this will help you to solve your issue.

Thank you!

Answered By – Gimhan Ranasinghe

Answer Checked By – David Marino (AngularFixing Volunteer)

Leave a Reply

Your email address will not be published.