I am having trouble with accessing the keys/values/entries in an object (array), slightly changing that object and pushing it to a new empty object (newArray). I can access the keys, values & entries but cannot change them.
The code below works fine but I would like to make it less specific and more generic so I can use this function elsewhere too.
I have tried using Object.keys(), Object.values() and Object.entries(), along with keyof typeof x but to no avail as .replace() won't work on the object.
The object is downloaded as a CSV and I use double quotes to separate fields as fields may contain commas and will throw the CSV fields off if kept in.
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 with 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);
Object should look like this:
{
"addressLine1": "\"The Road\"",
"addressLine2": "",
"town": "\"London\"",
"postcode": "\"SE1 5QH\"",
}
You could try not to "stringify" your objects and make it directly from the object.
Maybe something like this (I leave you a working example in here): https://codesandbox.io/s/dark-dawn-w85z3
let objArray = [
{
addressLine1: "anothernamefieldexampleline1",
addressLine2: "exampleline2",
town: "exampletown1",
postcode: "examplepostcode1"
},
{
addressLine1: "exampleline1b",
addressLine2: "exampleline2b",
town: "exampletown1b",
postcode: "examplepostcodeb"
}
];
let array = typeof objArray != "object" ? JSON.parse(objArray) : objArray;
let newArray = array.map((_itemObject) => {
let returnObject={};
let arrayKeyProperties = [];
for (const key in _itemObject) {
arrayKeyProperties.push(key);
};
console.log(arrayKeyProperties);
arrayKeyProperties.forEach(
(_prop) => returnObject[_itemObject[_prop]] = _itemObject[_prop]
);
return returnObject;
});
console.log(newArray);
I show image of output, with the created array with new objects with new field names (based on the value of the old ones).