How to Remove Specific Text / String Out of Array Object Values

Viewed 23

I am using Node.js 16.17 and Express.

Forgive me if this is answered elsewhere, if a solution exists elsewhere, please point me in that direction.

On my server side, I have an array with objects with properties and their values. I want to be able to remove specific text/string from the property values.

What I Have

I currently have an array with objects (and sometimes arrays and object nested within):

DataArray = 
[
  {
    page: {
      results: [
        {
          id: '1234',
          title: 'TextIWantA **(Text) I Dont Want**',
          children: {
            page: {
              results: [
                {
                  id: '5678',
                  title: 'ChildA TextIWant **(Text I) Dont Want**',
                },
                {
                  id: '9101',
                  title: 'ChildB TextIWant **(Text I) Dont Want**',
                  children: {
                    page: {
                      results: [
                        {
                          id: 'abcd',
                          title: 'GrandchildA TextIWant **(Text I (Dont) Want**',
                        }
                      ]
                    }
                  }
                },
              ],
            },
          },
        },
        {
          id: '1121',
          title: 'TextIWantB **(Text) I Dont Want**',
        }
      ]
    }
  }
]

Desired Result

I want to be able to remove all of the variances of Text I Dont Want, so the end result would look like

DataArray = 
[
  {
    page: {
      results: [
        {
          id: '1234',
          title: 'TextIWantA',
          children: {
            page: {
              results: [
                {
                  id: '5678',
                  title: 'ChildA TextIWant',
                },
                {
                  id: '9101',
                  title: 'ChildB TextIWant',
                  children: {
                    page: {
                      results: [
                        {
                          id: 'abcd',
                          title: 'GrandchildA TextIWant',
                        }
                      ]
                    }
                  }
                },
              ],
            },
          },
        },
        {
          id: '1121',
          title: 'TextIWantB',
        }
      ]
    }
  }
]

Each title is unique and I don't seem able to find anything to even say I've tried this or that. I don't want to use .startswith or .length or .index and would prefer to avoid regex, and any examples using .replace in the following fashion don't seem to work:

const NewDataArr = DataArr;
var NewDataArr = NewDataArr .map(function(x){return x.replace(/ (Text) I Dont Want/g, '');});

How do reach into these property values and rip out the text I don't want?

Thank you for any help you can provide.

0 Answers
Related