let obj = { name : "raj" , age : 23 , second : {
name : "suraj" , location : "mumbai" } ,
third : { name : "arjun" , age : 34 , friend : {
name : "pratik" , status : "married" } } }
If we have objects inside object which have same key name "name" and we want to change value of all that to "nikhil". How can we do it at once.
This question ask me in an Interview.
How can we do that , if anyone know please let me know.
Just want to change value of all "name" key to "nikhil".
3
Answers
recursion is your friend, you have to traverse to all node recursively and change with value.
remember one thing it will change to original
Object
.As others mentioned this could be done using recursion.
However, if you’re looking for a more concise way to achieve the same result, you can use a library like Lodash, which provides utility functions for working with objects and arrays. Here’s how you can do it using Lodash:
output:
Using Lodash’s
_.transform
and_.isObject
functions simplifies the code and makes it more readable. Lodash also has built-in handling for deep traversal and modification of objects, which can be more efficient in certain scenarios.