javascript - Establecer dinámicamente la propiedad de un objeto anidado
Tengo un objeto que podría tener cualquier número de niveles de profundidad y podría tener cualquier propiedad existente. Por ejemplo:
var obj = {
db: {
mongodb: {
host: 'localhost'
}
}
};
Sobre eso me gustaría establecer (o sobrescribir) propiedades de la siguiente manera:
set('db.mongodb.user', 'root');
// or:
set('foo.bar', 'baz');
Donde la cadena de propiedad puede tener cualquier profundidad, y el valor puede ser de cualquier tipo/cosa.
Los objetos y arreglos como valores no necesitan ser fusionados, si la clave de la propiedad ya existe.
El ejemplo anterior produciría el siguiente objeto:
var obj = {
db: {
mongodb: {
host: 'localhost',
user: 'root'
}
},
foo: {
bar: baz
}
};
¿Cómo puedo realizar una función así?
Respuesta #1
Esta función, usando los argumentos que especificaste, debería agregar/actualizar los datos en el contenedor obj. Nota que necesitas hacer un seguimiento de cuáles elementos en el esquema de obj son contenedores y cuáles son valores (cadenas, enteros, etc.) de lo contrario empezarás a lanzar excepciones.
obj = {}; // global object
function set(path, value) {
var schema = obj; // a moving reference to internal objects within obj
var pList = path.split('.');
var len = pList.length;
for(var i = 0; i < len-1; i++) {
var elem = pList[i];
if( !schema[elem] ) schema[elem] = {}
schema = schema[elem];
}
schema[pList[len-1]] = value;
}
set('mongo.db.user', 'root');
Respuesta #2
Lodash tiene un método _.set().
_.set(obj, 'db.mongodb.user', 'root');
_.set(obj, 'foo.bar', 'baz');
Respuesta #3
Solo escribo una pequeña función usando ES6 + recursión para lograr el objetivo.
updateObjProp = (obj, value, propPath) => {
const [head, ...rest] = propPath.split('.');
!rest.length
? obj[head] = value
: this.updateObjProp(obj[head], value, rest.join('.'));
}
const user = {profile: {name: 'foo'}};
updateObjProp(user, 'fooChanged', 'profile.name');
Lo usé mucho en React para actualizar el estado, me funcionó bastante bien.
Respuesta #4
Un poco tarde, pero aquí hay una respuesta más sencilla, sin usar bibliotecas:
/**
* Dynamically sets a deeply nested value in an object.
* Optionally "bores" a path to it if its undefined.
* @function
* @param {!object} obj - The object which contains the value you want to change/set.
* @param {!array} path - The array representation of path to the value you want to change/set.
* @param {!mixed} value - The value you want to set it to.
* @param {boolean} setrecursively - If true, will set value of non-existing path as well.
*/
function setDeep(obj, path, value, setrecursively = false) {
path.reduce((a, b, level) => {
if (setrecursively && typeof a[b] === "undefined" && level !== path.length){
a[b] = {};
return a[b];
}
if (level === path.length){
a[b] = value;
return value;
}
return a[b];
}, obj);
}
Esta función que hice puede hacer exactamente lo que necesitas y un poco más.
digamos que queremos cambiar el valor objetivo que está profundamente anidado en este objeto:
let myObj = {
level1: {
level2: {
target: 1
}
}
}
Así que llamaríamos a nuestra función así:
setDeep(myObj, ["level1", "level2", "target1"], 3);
resultará en:
miObj={ nivel1: { nivel2: { objetivo: 3 } } }
Establecer la bandera de establecer recursivamente en verdadero configurará los objetos si no existen.
setDeep(myObj, ["new", "path", "target"], 3, true);
resultará en esto:
obj = myObj = {
new: {
path: {
target: 3
}
},
level1: {
level2: {
target: 3
}
}
}
Respuesta #5
Podemos usar una función recursiva:
/**
* Sets a value of nested key string descriptor inside a Object.
* It changes the passed object.
* Ex:
* let obj = {a: {b:{c:'initial'}}}
* setNestedKey(obj, ['a', 'b', 'c'], 'changed-value')
* assert(obj === {a: {b:{c:'changed-value'}}})
*
* @param {[Object]} obj Object to set the nested key
* @param {[Array]} path An array to describe the path(Ex: ['a', 'b', 'c'])
* @param {[Object]} value Any value
*/
export const setNestedKey = (obj, path, value) => {
if (path.length === 1) {
obj[path] = value
return
}
return setNestedKey(obj[path[0]], path.slice(1), value)
}
¡Es más simple!
Respuesta #6
Inspirado por la respuesta de @bpmason1:
function leaf(obj, path, value) {
const pList = path.split('.');
const key = pList.pop();
const pointer = pList.reduce((accumulator, currentValue) => {
if (accumulator[currentValue] === undefined) accumulator[currentValue] = {};
return accumulator[currentValue];
}, obj);
pointer[key] = value;
return obj;
}
const obj = {
boats: {
m1: 'lady blue'
}
};
leaf(obj, 'boats.m1', 'lady blue II');
leaf(obj, 'boats.m2', 'lady bird');
console.log(obj); // { boats: { m1: 'lady blue II', m2: 'lady bird' } }Respuesta #7
Se me ocurrió mi propia solución usando puro ES6 y recursión que no muta el objeto original.
const setNestedProp = (obj = {}, [first, ...rest] , value) => ({
...obj,
[first]: rest.length
? setNestedProp(obj[first], rest, value)
: value
});
const result = setNestedProp({}, ["first", "second", "a"],
"foo");
const result2 = setNestedProp(result, ["first", "second", "b"], "bar");
console.log(result);
console.log(result2);Respuesta #8
ES6 también tiene una manera bastante genial de hacer esto usando Nombre de Propiedad Computada y Parámetro Rest.
const obj = {
levelOne: {
levelTwo: {
levelThree: "Set this one!"
}
}
}
const updatedObj = {
...obj,
levelOne: {
...obj.levelOne,
levelTwo: {
...obj.levelOne.levelTwo,
levelThree: "I am now updated!"
}
}
}
Si levelThree es una propiedad dinámica, es decir, para establecer cualquiera de las propiedades en levelTwo, puedes usar [propertyName]: "¡Ahora estoy actualizado!" donde propertyName contiene el nombre de la propiedad en levelTwo.
