0

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

3
  • have you tried regexes : jsonText.replace(/(\r\n|\n|\r)/gm, ""); ? Commented Feb 16, 2022 at 17:25
  • yes i use it and no change Commented Feb 16, 2022 at 17:37
  • Post some code so we can see what you've tried so far. Commented Feb 16, 2022 at 17:43

1 Answer 1

1

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);

Sign up to request clarification or add additional context in comments.

7 Comments

Hi, the problem with my in keys not value
You could change Object.values to Object.keys
This is the structure of the json object how to access the key {"SOH":[{"MN":"asdf","Part\r\nNumber":"1234"},{"MN":"asdf2","Part\r\nNumber":"12343"}]}
I want to modify the key and the value remains the same
{"SOH":[{"MN":"asdf","PartNumber":"1234"},{"MN":"asdf2","PartNumber":"12343"}]}
|

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.