I am struggling with accessing and modifying the keys, values, and entries in an object (array), then transferring it to a new empty object (newArray). While I can retrieve the keys, values & entries, I'm facing difficulty making changes to them.
The code below is functional, but I aim to generalize it for broader usage across different scenarios.
I have experimented with Object.keys(), Object.values(), Object.entries(), as well as keyof typeof x, yet haven't been successful as .replace() method doesn't work smoothly with objects.
The object is obtained as a CSV file where double quotes are used to separate fields due to potential commas disrupting the structure.
let array = typeof objArray != 'object' ? JSON.parse(objArray) : objArray;
let newArray = [];
array.forEach(s => {
let x = JSON.parse(JSON.stringify(s));
x.addressLine1 = x.addressLine1.replace(x.addressLine1, `"${x.addressLine1}"`);
x.addressLine2 = x.addressLine2 ? x.addressLine2.replace(x.addressLine2, `"${x.addressLine2}"`) : '';
x.town = x.town.replace(x.town, `"${x.town}"`);
x.postcode = x.postcode.replace(x.postcode, `"${x.postcode}"`);
newArray.push(x);
});
Attempt utilizing keyof typeof:
array.forEach(s => {
let x = JSON.parse(JSON.stringify(s));
let property: keyof typeof x;
for (property in x) {
property = property ? property.replace(property, `"${property}"`) : '';
newArray.push(x);
Desired format of the object:
{
"addressLine1": "\"The Road\"",
"addressLine2": "",
"town": "\"London\"",
"postcode": "\"SE1 5QH\"",
}