Suppose I want to replace all Json items before colons with my array respectively using JavaScript, how do I go about it.
As you may see below, is a Json object representing column names and first row. I want to replace column names position-wise with values from an array shown below.
// Json object
const Json = "{id: '1', name: 'Abednego Nasila', Reg: '123'}"
And below is my array
//array variable
const arr = ['myId', 'Student_name', 'Adm.no']
My desired output should be as shown below:
"{myId: '1', Student_name: 'Abednego Nasila', Adm.no = '123'}"
Thanks
Any help help will be appreciated.
2
Answers
The problem is that your source JSON is, in fact, not a valid JSON string.
Therefore, to convert it into an object, I’m using a bit hackish solution. I wouldn’t recommend using this approach in a real production environment. You probably want to convert your source string into a valid JSON first instead.
Anyway, here is how this can be achieved:
Here is a function that replaces the keys in a given JSON String with keys from a given Array.
Now go study: