Tengo un objeto y quiero construir una función, tomo el objeto y el nombre de una propiedad y la función devuelve el valor de esa propiedad, si ves que vas a decir, "Oh, es tan fácil, solo usa comillas dobles o notación de puntos para acceder a ese valor" PERO quiero que la función me devuelva no solo el valor de la propiedad de primer nivel, sino también su anidado si hay algún objeto dentro de ese objeto y busque ese nombre de propiedad si existe acumule el valor en la matriz y devuelva el resultado:
let obj = { a: { b: "value of b", }, b: "another value of b", c: { d: [1, 2, 3], }, }; // input output getDeepValuesProperty(obj, "a"); //{ b: "value of b" } getDeepValuesProperty(obj, "b"); //["value of b", "another value of b"] getDeepValuesProperty(obj, "d"); //[1, 2, 3] let obj = { a: { b: "value of b", }, b: "another value of b", c: { d: [1, 2, 3], }, }; function getDeepValuesProperty(object, propertyName) { if (object[propertyName]) { return object[propertyName]; } else if (typeof object[propertyName] == "object") { return getDeepValuesProperty(object[propertyName], propertyName); } } console.log(getDeepValuesProperty(obj, "a")); //{ b: "value of b" } console.log(getDeepValuesProperty(obj, "b")); //another value of b console.log(getDeepValuesProperty(obj, "d")); //undefined El primer ejemplo funcionó, pero el segundo no funciona como esperaba y devuelve solo el último valor, el tercer ejemplo devuelve undefined No sé por qué sucede esto, ¿me pierdo algo en la función de recursión?
Su función getDeepValuesProperty() devuelve instantáneamente el valor de su objeto if una de sus declaraciones coincide. Si necesita todas las ocurrencias, necesita agregar estos resultados, usando una función .reduce por ejemplo.
let obj = { a: { b: "value of b", }, b: "another value of b", c: { d: [1, 2, 3], }, }; function getDeepValuesProperty(object, propertyName) { return Object.entries(object).reduce((values, [key, value]) => { if (key === propertyName) { return [...values, value]; } else if (typeof value === 'object') { return [...values, ...getDeepValuesProperty(value, propertyName)]; } return values; }, []); } console.log(getDeepValuesProperty(obj, 'a')); // [ { b: 'value of b' } ] console.log(getDeepValuesProperty(obj, 'b')); // [ 'value of b', 'another value of b' ] console.log(getDeepValuesProperty(obj, 'd')); // [ [ 1, 2, 3 ] ]Use una función contenedora en la que declare una matriz vacía, envíe los resultados a esa matriz y los devuelva al final.
let obj = { a: { b: "value of b", }, b: "another value of b", c: { d: [1, 2, 3], }, }; function getDeepValuesProperty(object, propertyName) { const output = []; function getDeep(object, propertyName) { for (let prop in object) { if (prop === propertyName) output.push(object[prop]) if (typeof object[prop] === 'object') { getDeep(object[prop], propertyName) } } } getDeep(object, propertyName); return output } console.log(getDeepValuesProperty(obj, "a")); //{ b: "value of b" } console.log(getDeepValuesProperty(obj, "b")); // "value of b", "another value of b"b console.log(getDeepValuesProperty(obj, "d")); // [1,2,3]Puede dividir un objeto en entradas de la siguiente manera:
Object.entries({a: 42, b: 43}) // [['a', 42], ['b', 43]] // ^ ^ ^ ^ // key value key valueLuego puede iterar la lista de entradas y tomar algunas decisiones:
El nombre de la propiedad es…
El nombre de la propiedad no coincide y...
Cada vez que inspeccionas , haces una llamada recursiva sobre ese valor. El resultado de cada llamada se agrega en una matriz.
Aquí hay una solución recursiva curry que obtiene el valor de todas las propiedades en cualquier profundidad de a objeto, incluidos los objetos contenidos en matrices:
const get_all_properties_by_name = name => function loop(obj) { return Object.entries(obj).flatMap(([k, v]) => { const match = k == name; const is_arr = Array.isArray(v); const is_obj = typeof v == 'object' && v !== null; if (match && is_arr) return [v].concat(v.flatMap(loop)); if (match && is_obj) return [v].concat(loop(v)); if (match) return [v]; return is_arr ? v.flatMap(loop) : loop(v); }); } const get_a = get_all_properties_by_name('a');Y aquí hay algunos resultados:
get_a({ a: 42 , b: { a: 43 } , c: { a: 44 , d: { a: 45 , e: { a: 46 } }} , d: [ { a: 47 } , { b: { a: 48 }} , { c: 100 }] , e: { f: [ { a: 49 } , { b: { c: { d: { a: 50 }}}}]} , f: { a: { a: { a: 51 }}} , g: { a: [ 52 , 53 ] , b: { a: [ 54 , 55 , { a: 56 } , { b: { a: 57 }} , { a: [ 58 , 59 , [{ a: 60 }] ]} ]}} , h: 61}); /* [ 42 , 43 , 44 , 45 , 46 , 47 , 48 , 49 , 50 , {a: {a: 51}} , {a: 51} , 51 , [52, 53] , [54, 55, {a: 56}, {b: {a: 57}}, {a: [58, 59, [{a: 60}]]}] , 56 , 57 , [58, 59, [{ a: 60 }]] , 60 ] */