0

My question is how to change or use the variable name instead of value; I want to use this snippet:

jsonData.forEach((data)=>{
      data.newName= data.api_name;
      delete data.api_name;
})

to change the incoming JSON data's key identifier and get that "oldName" from a variable like this

var api_name = "fName";

So for example if this data comes from JSON:

[{
  "fName": "John",
  "lname": "Smith"
} {
  "fName": "Jane",
  "lname": "hardy"
}]

and want to have this:

[{
  "person_name": "John",
  "lname": "Smith"
} {
  "person_name": "Jane",
  "lname": "hardy"
}]

but if I do it like the snippet I will get error because the JSON doesn't have api_name as it's key identifier. I hope that I explained enough. appreciate any help

mssoheil
  • 110
  • 1
  • 14

2 Answers2

0

Try with data[newName]= data[api_name];

eg newName= 'fName';

api_name='apiName'

Mudit
  • 54
  • 6
0

Use data[api_name] instead of data.api_name . Read more about property accessors.

let jsonData = [{
  "fName": "John",
  "lname": "Smith"
},{
  "fName": "Jane",
  "lname": "hardy"
}];

let api_name = "fName";

jsonData.forEach((data)=>{
   data.newName= data[api_name];
   delete data[api_name];
})

console.log(jsonData);
Aivan Monceller
  • 4,636
  • 10
  • 42
  • 69