1

I have a nested object that includes several keys, these keys also include title and children. children is an array of the objects that have title and children keys too. (they look like a tree) how can I search and replace one word or a part of a title's value?

const object = {
    id: 'uuid',
    title: 'hello You',
    type: number,
    visibility: true,
    children: [
        {
            id: 'uuid',
            title: 'You don't have any comments...',
            type: number,
            visibility: true,
            children: [{...}, {...}, ...],
            key1: {...},
            key2: [{...}]
        },
        {
            id: 'uuid',
            title: 'You your problem is not with json...',
            type: number,
            visibility: true,
            children: [{...}, {...}, ...],
            key1: {...},
            key2: [{...}]
       }
    ],
    key1: {...},
    key2: [{...}]
}

search you and replace world on title

output = {
    id: 'uuid',
    title: 'hello world',
    type: number,
    visibility: true,
    children: [
        {
            id: 'uuid',
            title: 'world don't have any comments...',
            type: number,
            visibility: true,
            children: [{...}, {...}, ...],
            key1: {...},
            key2: [{...}]
        },
        {
            id: 'uuid',
            title: 'world your problem is not with json...',
            type: number,
            visibility: true,
            children: [{...}, {...}, ...],
            key1: {...},
            key2: [{...}]
       }
    ],
    key1: {...},
    key2: [{...}]
}

1 Answer 1

1

You can try using recursive strategy to find any key within an array and also search on their children as well.

function recursive (newArray) {
  newArray.map(obj => {
    if (obj.title) {
      obj.title = obj.title.replace(/You/g, 'world')
    }
    if (obj.children) {
      return recursive (obj.children)
    }
  })
  return newArray
}

using the function

let arr = [object]

recursive(arr)
Sign up to request clarification or add additional context in comments.

Comments

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.