Business
Jobs
  • About Us
  • Solutions
    • Job Postings
      Post your job and receive qualified candidates in 48h.
    • Candidate Assessments
      500+ technical and psychological tests, plus anti-fraud.
    • Headhunting
      Tailor-made executive search from start to finish.
    • Payroll + EOR
      Payroll dispersal and EOR across 15+ LATAM countries.
  • Pricing
  • Jobs

0

274
Views
Iterando una cadena JSON con mapas en JS

He estado tratando de iterar en un JSON que contiene un mapa dentro de un mapa durante horas sin suerte...

Esta es la cadena JSON:

 { "P31": { "wikibase-entityid": "Q16603799" }, "P227": { "string": "1084653095" }, "P1001": { "wikibase-entityid": "Q183" }, "P1448": { "monolingualtext": "Verordnung über Sicherheit und Gesundheitsschutz bei der Verwendung von Arbeitsmitteln" }, "P1813": { "monolingualtext": "Betriebssicherheitsverordnung" }, "P7677": { "string": "betrsichv_2015" }, "P580": { "time": "+2002-10-03T00:00:00Z" }, "P2671": { "string": "/g/1224z0c0" }, "P9696": { "string": "11477" } }

Imagen para una referencia visual fácil: ingrese la descripción de la imagen aquí

Nota: cada propiedad puede tener varios valores.

Básicamente quiero crear un ciclo dentro del cual tengo acceso a la propiedad (PXXX, lo primero), el tipo de propiedad (clave en el mapa interno) y el valor de la propiedad (valor en el mapa interno).

Intenté convertir la cadena en un Mapa usando "nuevo Mapa (JSON.parse (jsonStr))", "nuevo Mapa (Object.entries (jsonStr))" y otros sin suerte.

Además, traté de iterar dentro de él con un "for (var key in obj)" y con un "myMap.forEach((value_propertyInfo, key_propertyName) => {...}" sin suerte tampoco.

Algunas veces parece que estoy iterando carácter por carácter, mientras que otras simplemente arrojan un error que dice que el mapa no es iterable.

¿Alguien sabe qué debo usar en su lugar?

¡Gracias!

about 4 years ago · Juan Pablo Isaza
3 answers
Answer question

0

No te molestes con Map . Simplemente itere sobre el objeto de datos, registre la clave y luego registre las entradas del objeto de esa propiedad, y registre la clave y el valor.

 const data = {"P31":{"wikibase-entityid":"Q16603799"},"P227":{"string":"1084653095"},"P1001":{"wikibase-entityid":"Q183"},"P1448":{"monolingualtext":"Verordnung über Sicherheit und Gesundheitsschutz bei der Verwendung von Arbeitsmitteln"},"P1813":{"monolingualtext":"Betriebssicherheitsverordnung"},"P7677":{"string":"betrsichv_2015"},"P580":{"time":"+2002-10-03T00:00:00Z"},"P2671":{"string":"/g/1224z0c0"},"P9696":{"string":"11477"}}; for (const key in data) { console.log(key); const entries = Object.entries(data[key]); for (const [key, value] of entries) { console.log(key, value); } }

about 4 years ago · Juan Pablo Isaza Report

0

La estructura de datos es realmente subóptima. Utiliza nombres de propiedades variables, "PXXX" en los objetos externos y el tipo en los internos. Lo ideal es que siempre tenga nombres de propiedad fijos y solo varíen los valores. Lo mejor sería esta forma de matriz e iteración.

 a=[ [prop, type, value], [prop, type, value], // {"prop": prop, "type": type, "value":value} is also good ... ] for(const [prop, type, value] of a) handleProperty(prop, type, value);

Casi podemos llegar a esto transformando la cadena json antes de analizar:

 s='{"P31":{"wikibase-entityid":"Q16603799"},"P227":{"string":"1084653095"},"P1001":{"wikibase-entityid":"Q183"},"P1448":{"monolingualtext":"Verordnung über Sicherheit und Gesundheitsschutz bei der Verwendung von Arbeitsmitteln"},"P1813":{"monolingualtext":"Betriebssicherheitsverordnung"},"P7677":{"string":"betrsichv_2015"},"P580":{"time":"+2002-10-03T00:00:00Z"},"P2671":{"string":"/g/1224z0c0"},"P9696":{"string":"11477"}}' data=JSON.parse(s.replaceAll(':{',':[').replaceAll('":"','","').replaceAll('"}','"]')) /* We now have data={ prop:[type, value], prop:[type, value], ... }*/ for(const [prop,[type, value]] of Object.entries(data)) console.log(prop,type,value)

usando Object.entries() y asignación de desestructuración .

Si no desea transformar la cadena JSON, deberá usar

about 4 years ago · Juan Pablo Isaza Report

0

Puede recorrer las propiedades del objeto y extraer para cada elemento propertyId, propertyName y propertyValue de esta manera:

 let o = //the object coming from the json Object.keys(o).forEach( (propertyId) => { //I'm taking for granted that each item will contain one property only and that property will be what we are looking for let propertyType = Object.keys( o[propertyId] )[0]; let propertyValue = o[propertyId][propertyType]; });
about 4 years ago · Juan Pablo Isaza Report
Answer question
Find remote jobs

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post vacancy Pricing Sales
Legal
Terms and conditions Privacy policy
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Show me some job opportunities
There's an error!