1

As the title mention, I want to replace the values of a particular key in a javascript object.

Sample Array -

[{
    title: "stackflow",
    child: [{
        title: 'stack',
        child: [{
            title: 'javascript stack',
            child: [{
                title: 'stack node',
                child: []
            }]
        }]
    }]
}]

Value to be replaced key is title and value stack with stackoverflow anywhere in the array.

I already google and tried many solutions but didn't get the proper solution for this. Any reference link or solution most welcome, Thanks in advance.

2
  • Just to clarify: are you trying to iterate over your object, checking the title keys and then, if the value is "stack", replace it with "stackoverflow"? Commented Nov 18, 2020 at 3:00
  • 1
    @BrunoMonteiro yes Commented Nov 18, 2020 at 3:01

4 Answers 4

3

You can use map and a recursive function:

const oldItems = [{
  title: "stackflow",
  child: [{
    title: 'stack',
    child: [{
      title: 'javascript stack',
      child: [{
        title: 'stack node',
        child: []
      }]
    }]
  }]
}];

const replace = (items) =>
  items.map((item) => ({
    ...item,
    title: item.title === 'stack' ? 'stackoverflow' : item.title,
    child: replace(item.child)
  }));

const newItems = replace(oldItems);
console.log(newItems);

Live Demo

And if you want to replace all instances of stack - including those that sit inside longer strings - then change the following line:

title: item.title === 'stack' ? 'stackoverflow' : item.title,

to:

title: item.title.replaceAll('stack', 'stackoverflow'),

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

1 Comment

Nice answer. Stack Overflow allows you to embed runnable code snippets using the [<>] button, I've added one in for you
2

This is another solution, probably the performance is poor against other solutions.

const array = [{
    title: "stackflow",
    child: [{
        title: 'stack',
        child: [{
            title: 'javascript stack',
            child: [{
                title: 'stackoverflow stack',
                child: []
            }]
        }]
    }]
}];

JSON.parse(JSON.stringify(array).replace(/"title":"stack"/g,'"title":"stackoverflow"'))

1 Comment

This is a pretty smart and clean way to do it!
1

You can use a recursive function.

Updated the answer to replace all the exact stack string.

const array = [{
    title: "stackflow",
    child: [{
        title: 'stack',
        child: [{
            title: 'javascript stack',
            child: [{
                title: 'stackoverflow stack',
                child: []
            }]
        }]
    }]
}]

const replaceAllOccurs = (arr) => (
    arr.map(({ title, child }) => (
        {
            title: title.replace(/\bstack\b/g, 'stackoverflow'),
            child: replaceAllOccurs(child)
        }
    ))
)

console.log(replaceAllOccurs(array));

Comments

1

@RoMilton has a good answer, but just wanted to contribute with another option for dynamic values:

const sampleObj = [{
  title: "stackflow",
  child: [{
      title: 'stack',
      child: [{
          title: 'javascript stack',
          child: [{
              title: 'stack node',
              child: []
          }]
      }]
  }]
}]

const findAndReplace = (obj, key, value, newValue) => {
  return obj.map((item) => {
    if (item[key] === value) {
      return {
        ...item,
        [key]: newValue,
      }
    } else {
      const objKeys = Object.keys(item)
      const arrayKey = objKeys.find((key) => Array.isArray(item[key]))
      return {
        ...item,
        [arrayKey]: findAndReplace(item[arrayKey], key, value, newValue)
      }
    }
  })
}

const updatedObj = findAndReplace(sampleObj, 'title', 'stack', 'stackoverflow')
console.log(updatedObj)

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.