¿Escriba una función que debería tomar una matriz de objetos y debería reemplazar un valor particular de la clave?
por ejemplo: en el objeto a continuación, todo el valor de "bar" debe reemplazarse por "foo-bar"
let obj = {
a: "foo",
b: "bar",
c: {
d: "foo",
e: "bar",
f: {
g: "test",
h: "bar",
}
}
}
Nota: Todas las propiedades de objetos anidados también deben reemplazarse
Recorra recursivamente todas las claves.
const obj = {
a: 'foo',
b: 'bar',
c: {
d: 'foo',
e: 'bar',
f: {
g: 'test',
h: 'bar',
},
},
};
function replaceValuesInObj(o, targetValue, replaceValue) {
Object.keys(o).forEach((key) => { // forEach key in the object
if (o[key] === targetValue) o[key] = replaceValue; // is the value your condition? set it to 'foo-bar'
if (typeof o[key] === 'object' && o[key] !== null) { // if the key is an object (call the function recursively)
replaceValuesInObj(o[key], targetValue, replaceValue);
}
});
}
replaceValuesInObj(obj, 'bar', 'foo-bar');
console.log(obj);