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.
Advertisement
Answer
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);
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'),