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

108
Vistas
Analizar la cadena de pares de valores clave donde la clave aparece varias veces en el objeto

Tengo una cadena en el siguiente formato:

"foo: bar, foo: baz, some: thing, some: other, third: other"

Y lo que quiero es un objeto:

 { foo: [bar, baz], some: [other, thing], third: [other] }

¿Cómo podría lograr esto de una manera inteligente?

about 4 years ago · Santiago Trujillo
3 Respuestas
Responde la pregunta

0

Simplemente puede dividir en , dejándolo con los pares de valores clave. Luego puede dividir cada par en : y luego agregar la clave en un objeto y almacenar los valores en una matriz.

 let str = "foo: bar, foo: baz, some: thing, some: other, third: other"; let obj = {}; str.split(", ").forEach((pair) => { let [key, value] = pair.split(": "); if (obj[key]) { obj[key].push(value); } else { obj[key] = [value]; } }); console.log(obj);

about 4 years ago · Santiago Trujillo Denunciar

0

Primero, tenemos que dividir la matriz en base a comas para eso, podemos usar

 const commaSepArray = "foo: bar, foo: baz, some: thing, some: other, third: other".split(",")

entonces commaSepArray tendrá

 ['foo: bar', ' foo: baz', ' some: thing', ' some: other', ' third: other'] // which looks like a key-value pair , now we have to split it again and create an object like const Obj = {} commaSepArray.map((x)=>{ const keyVal = x.split(":"); if(Obj[keyVal[0]]){ Obj[keyVal[0]].push(keyVal[1]) }else { Obj[keyVal[0]] = [keyVal[1]] } })
about 4 years ago · Santiago Trujillo Denunciar

0

Creo que estas son las respuestas:

 const string = "foo: bar, foo: baz, some: thing, some: other, third: other" const splitString = string.split(', '); let obj = {} // assign every key to the object and set the value to an empty array splitString.forEach((string) => { const innerSplitString = string.split(': '); obj[innerSplitString[0]] = [] }) // push every value into the [key]-[empty array value] of the object splitString.forEach((string) => { const innerSplitString = string.split(': '); obj[innerSplitString[0]].push(innerSplitString[1]) }) // sort the [key]-[array value] for(const key in obj) { obj[key].sort() } console.log(obj)

Espero que esto te ayude, gracias

about 4 years ago · Santiago Trujillo 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