Empresas
Empregos
  • Sobre nós
  • Soluções
    • Publicação de vagas
      Publique sua vaga e receba candidatos qualificados em 48h.
    • Avaliações de candidatos
      Mais de 500 testes técnicos e psicológicos, mais anti-fraude.
    • Headhunting
      Busca executiva personalizada do início ao fim.
    • Folha de Pagamento + EOR
      Dispersão de folha e EOR em mais de 15 países da LATAM.
  • Preços
  • Empregos

0

122
Visualizações
¿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 Respostas
Responde à pergunta

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 Relatório

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 Relatório
Responde à pergunta
Encontrar trabalhos remotos

Descubra a nova forma de encontrar um emprego!

melhores empregos
Principais categorias de trabalho
Empresas
Postar vaga Preços Comercial
Jurídico
Termos e Condições Política de privacidade
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomende algumas ofertas para mim
Preciso de ajuda