Empresas
Empregos
  • Sobre nós
  • Soluções
    • Publicação de vagas
      Publique sua vaga e receba candidatos qualificados em 48h.
    • Avaliações de candidatos
      Mais de 500 testes técnicos e psicológicos, mais anti-fraude.
    • Headhunting
      Busca executiva personalizada do início ao fim.
    • Folha de Pagamento + EOR
      Dispersão de folha e EOR em mais de 15 países da LATAM.
  • Preços
  • Empregos

0

168
Visualizações
¿Cómo obtener todos los valores de un nombre de propiedad en un objeto?

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?

about 4 years ago · Santiago Trujillo
3 Respostas
Responde à pergunta

0

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 ] ]
about 4 years ago · Santiago Trujillo Relatório

0

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]

about 4 years ago · Santiago Trujillo Relatório

0

Puede dividir un objeto en entradas de la siguiente manera:

 Object.entries({a: 42, b: 43}) // [['a', 42], ['b', 43]] // ^ ^ ^ ^ // key value key value

Luego puede iterar la lista de entradas y tomar algunas decisiones:

El nombre de la propiedad es…

  1. una coincidencia y el valor no es ni una matriz ni un objeto: mantener el valor
  2. una coincidencia y un valor es una matriz: mantenga la matriz e inspeccione cada elemento
  3. una coincidencia y el valor es un objeto: mantener el objeto e inspeccionar el objeto

El nombre de la propiedad no coincide y...

  1. el valor no es ni una matriz ni un objeto: valor de descarte
  2. el valor es una matriz: inspeccionar cada elemento
  3. el valor es un objeto: inspeccionar objeto

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 ] */
about 4 years ago · Santiago Trujillo Relatório
Responde à pergunta
Encontrar trabalhos remotos

Descubra a nova forma de encontrar um emprego!

melhores empregos
Principais categorias de trabalho
Empresas
Postar vaga Preços Comercial
Jurídico
Termos e Condições Política de privacidade
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomende algumas ofertas para mim
Preciso de ajuda