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

121
Views
¿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 answers
Answer question

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 Report

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 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!