Messi just decided to open a new blog and test it while playing the best football you can imagine:
jsxconst blog = { 'posts': { '0': { 'user': 'Messi', 'message': 'Hey!', 'replies': { '0': { 'user': 'Messi', 'message': 'It me again', 'replies': { '0': { 'user': 'Messi', 'message': 'This is my last message' } } } } }, '1': { 'user': 'Messi', 'message': 'Hey!' } } }
Let's suppose that we want to replace a property; we could iterate through every object property recursively (hard way) or we could just transform the object into a string and replace the desired properties (easy way).
Example:
jsxconst replaceProperty = (object, oldProperty, newProperty, oldValue, newValue) => { // We convert the object into a string let stringify = JSON.stringify(object); // We replace the old property and value with the new property and value let replaced = stringify.split(`"${oldProperty}":"${oldValue}"`).join(`"${newProperty}":"${newValue}"`); // We convert the string into json again let json = JSON.parse(replaced); return json; }
And that's it. Let's imagine that Cristiano wants to copy Messi's blog. He could execute the past function as follows:
jsxlet CristianoBlog = replaceProperty(blog, 'user', 'player', 'Messi', 'Cristiano'); console.log(CristianoBlog); /* { 'posts': { '0': { 'player': 'Cristiano', 'message': 'Hey!', 'replies': { '0': { 'player': 'Cristiano', 'message': 'It me again', 'replies': { '0': { 'user': 'Cristiano', 'message': 'This is my last message' } } } } }, '1': { 'player': 'Messi', 'message': 'Hey!' } } } */
Hi, I'm Erik, an engineer from Barcelona. If you like the post or have any comments, say hi.