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

123
Vistas
¿Cómo puedo analizar una matriz de objetos que están relacionados para reducirlos condicionalmente?

tengo una matriz

 [ { "id": 19, "name": "rice", "food_group": null, "created_at": "2022-03-15T02:38:17.911Z", "updated_at": "2022-03-15T02:38:17.911Z" }, { "id": 20, "name": "water", "food_group": null, "created_at": "2022-03-15T02:38:17.942Z", "updated_at": "2022-03-15T02:38:17.942Z" }, { "id": 8, "recipe_id": 19, "ingredient_id": 19, "quantity": 1, "measurement_unit": "cup", "created_at": "2022-03-15T02:38:17.932Z", "updated_at": "2022-03-15T02:38:17.932Z" }, { "id": 9, "recipe_id": 19, "ingredient_id": 20, "quantity": 23, "measurement_unit": "cup", "created_at": "2022-03-15T02:38:17.945Z", "updated_at": "2022-03-15T02:38:17.945Z" } ]

Y quiero reducir estos objetos a dos objetos que representen el ingrediente y las medidas, haciéndolo visible. Dado que el ingrediente_id está disponible en el objeto de medición/cantidad, creo que esto es factible, pero estoy luchando por ver cómo hacerlo.

Tengo una caja de arena aquí donde he estado intentando

Entonces, idealmente, la matriz se convertiría en

[{"arroz": { "unidad_de_medida": taza, cantidad: 1}}...]

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

0

Si bien esta cantidad de manipulación de datos es definitivamente algo mejor hecho en el back-end, es totalmente factible en el front-end con JavaScript.

Dividiría manualmente la matriz en los dos tipos y luego crearía una nueva matriz de todos los ingredientes, pero completaría los detalles de medición coincidentes para cada uno.

 // separate the ingredients from the measurements const ingredientsArr = data.filter(x => x.name); const measurementsArr = data.filter(x => x.measurement_unit); // map the ingredients to a new array of objects const output = ingredientsArr.map(({ id, name }) => { // find matching measurement by ingredient id const matchingMeasurement = measurementsArr.find(x => x.ingredient_id === id); // return object that we want return { [name]: { measurement_unit: matchingMeasurement.measurement_unit, quantity: matchingMeasurement.quantity } } });
about 4 years ago · Juan Pablo Isaza Denunciar

0

Lo que está haciendo tiene fallas en caso de que haya varias recetas con los mismos ingredientes en la lista, por lo que probablemente sea mejor hacer lo contrario, de todos modos, lo siguiente es lo que pidió:

 var objs = [{ "id": 19, "name": "rice", "food_group": null, "created_at": "2022-03-15T02:38:17.911Z", "updated_at": "2022-03-15T02:38:17.911Z" }, { "id": 20, "name": "water", "food_group": null, "created_at": "2022-03-15T02:38:17.942Z", "updated_at": "2022-03-15T02:38:17.942Z" }, { "id": 8, "recipe_id": 19, "ingredient_id": 19, "quantity": 1, "measurement_unit": "cup", "created_at": "2022-03-15T02:38:17.932Z", "updated_at": "2022-03-15T02:38:17.932Z" }, { "id": 9, "recipe_id": 19, "ingredient_id": 20, "quantity": 23, "measurement_unit": "cup", "created_at": "2022-03-15T02:38:17.945Z", "updated_at": "2022-03-15T02:38:17.945Z" } ] var ingredients = [] var recipes = [] objs.forEach(obj => { if ('name' in obj) { ingredients.push(obj) } else { recipes.push(obj) } }) ingredients = ingredients.map(ingredient => { match = recipes.find(recipe => recipe.ingredient_id === ingredient.id ) return { [ingredient.name]: { measurement_unit: match.measurement_unit, quantity: match.quantity } } }) console.log(ingredients)

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