Empresas
Empleos
  • Sobre nosotros
  • Soluciones
    • Publicación de vacantes
      Publica tu vacante y recibe candidatos calificados en 48h.
    • Evaluación de candidatos
      500+ pruebas técnicas y psicológicas, más anti-fraude.
    • Headhunting
      Búsqueda ejecutiva a la medida de principio a fin.
    • Nómina + EOR
      Dispersión de nómina y EOR en más de 15 países de LATAM.
  • Precios
  • Empleos

0

142
Vistas
get value of object key and parent javascript and create a new object

I have an object that looks like the following:

const testObject = {
  "NameA": {
    "Name": {
      "_text": "Peter"
    }
  },
  "AgeA": {
    "_comment": "line=2",
    "age": {
      "_text": "21"
    }
  },
  "Birth": {
    "_comment": "line=3",
    "Birthday": {
      "DateTimeSignUTCOffset": {
        "Date": {
          "_text": "191201"
        },
        "Time": {
          "_text": "1123"
        },
      },
      "Test": {
        "Code": {
          "_text": "1234"
        }
      },
    }
  }
}

I am trying to find any key with the key _text and get the corresponding value and the parent key.

i.e.

const result = { 
    "Name": "Peter",
    "age": "21",
    "Date": "191201",
    "Time": "1123",
    "Code": "1234"
};

I have tried the following by looping through the object but am unable to figure it out.

const result = {};

const find_items = (object) => {
  console.log(Object.keys(object));
  Object.keys(object).map((item) => {
    console.log(object[item]);
    if(object[item] !== '_text') {
      find_items(object[item])
    } else {
      console.log(item)
    }
  });
};

find_items(testObject);

console.log(result);

Can someone could point me in the right direction?

about 4 years ago · Juan Pablo Isaza
3 Respuestas
Responde la pregunta

0

You could take a recursive approach and check for object and if _text property exist take the value with the outer key or get the entries from the recursive call with the object.

At the end build an object from all entries.

const
    flatEntries = object => Object
        .entries(object)
        .flatMap(([k, v]) => {
            if (v && typeof v === 'object') return '_text' in v
                ? [[k, v._text]]
                : flatEntries(v);
            return [];        
        });
    testObject = { NameA: { Name: { _text: "Peter" } }, AgeA: { _comment: "line=2", age: { _text: "21" } }, Birth: { _comment: "line=3", Birthday: { DateTimeSignUTCOffset: { Date: { _text: "191201" }, Time: { _text: "1123" } }, Test: { Code: { _text: "1234" } } } } },
    result = Object.fromEntries(flatEntries(testObject));

console.log(result);

about 4 years ago · Juan Pablo Isaza Denunciar

0

in English, what you want to do is:

create an empty object named "result", and then recursively iterate through the "object" object. each time you encounter a key linked to a sub-object which has a __text field, add that to the "result" object.

now just translate the above into JavaScript.

the keyword here is "recursively". your original code was not recursive.

about 4 years ago · Juan Pablo Isaza Denunciar

0

your idea is pretty good, but you want to find _text keys anywhere nested inside the object. To find inner, nested, keys, you need to recurse your function if the value of some key happens to be an object.

result = {}

find_text_keys = (haystack, label) => {
  Object.keys(ob).forEach(key => {
    if (key === '_text') {
      res[text] = ob["_text"];
    } else if (typeof(ob[key]) === "object") {
      find_text_keys(ob[key], key);
    }
  });
}

Then, calling the function with a default label f(object, "default_label") will populate the result dictionary as you desired.

about 4 years ago · Juan Pablo Isaza Denunciar
Responde la pregunta
Encuentra empleos remotos

¡Descubre la nueva forma de encontrar empleo!

Top de empleos
Top categorías de empleo
Empresas
Publicar vacante Precios Comercial
Legal
Términos y condiciones Política de privacidad
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomiéndame algunas ofertas
Necesito ayuda