I have a Json object from Excel sheet conversion and it probably comes with some keys with Line breaks and spaces I want a function to remove all line breaks and spaces from json object keys This is the structure of the json
{"SOH":[{"MN":"asdf","Part\r\nNumber":"1234"},{"MN":"asdf2","Part\r\nNumber":"12343"}]}
expected outcome
{"SOH":[{"MN":"asdf","PartNumber":"1234"},{"MN":"asdf2","PartNumber":"12343"}]}
Thanks for support
CodePudding user response:
You could use Object.entries()
, map()
and replace()
to recreate objects with replaced values.
const obj = {
"SOH": [
{ "MN": "asdf", "Part\r\nNumber": "1234" },
{ "MN": "asdf2", "Part\r\nNumber": "12343" }
]
};
const result = {
"SOH": obj.SOH.map(o => {
return Object.fromEntries(Object.entries(o).map(([k, v]) => [k.replace(/(\n|\s)/g, ""), v]));
})
};
console.log(result);
Or if you want to make it more dynamic.
const obj = {
"SOH": [
{ "MN": "asdf", "Part\r\nNumber": "1234" },
{ "MN": "asdf2", "Part\r\nNumber": "12343" }
],
"MOH": [
{ "MN": "asdf", "Part\r\nNumber": "1234" },
{ "MN": "asdf2", "Part\r\nNumber": "12343" }
],
"KOH": [
{ "MN": "asdf", "Part\r\nNumber": "1234" },
{ "MN": "asdf2", "Part\r\nNumber": "12343" }
]
};
const result = Object.fromEntries(Object.entries(obj).map(([k, v]) => {
return [k, v.map(x => Object.fromEntries(Object.entries(x).map(([kk, vv]) => [kk.replace(/(\n|\s)/g, ""), vv])))]
}));
console.log(result);