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

163
Views
Cómo concatenar el campo JSON en otro objeto

Estos son los datos en cuestión:

 [ { "id": 3, "owner": "http://localhost:8000/api/v1/users/3/", "ingredients": [ { "ingredient": { "id": 1, "category": "Fruit", "name": "Apple", "calories": 100.0, }, "numOf": 4 }, { "ingredient": { "id": 2, "category": "Vegetable", "name": "Potato", "calories": 10.0, }, "numOf": 3 } ], "total_number": 0 } ]

Quiero concatenar numOf en el ingredient principal hist para que mi tabla se represente correctamente Ahora mismo, dados 2 ingredientes, mi tabla tiene 4 filas

Editar

El resultado deseado debería verse así:

 [ { "id": 3, "owner": "http://localhost:8000/api/v1/users/3/", "ingredients": [ { "ingredient": { "id": 1, "category": "Fruit", "name": "Apple", "calories": 100.0, "numOf": 4, } }, { "ingredient": { "id": 2, "category": "Vegetable", "name": "Potato", "calories": 10.0, "numOf": 3, } } ], "total_number": 0 } ]

El archivo JSON que ve es la respuesta de mi servidor cuando se le preguntó sobre el refrigerador del usuario. Luego quiero mostrar todos sus ingredientes en una tabla. Así es como declaro la matriz en VueJS:

 import axios from 'axios' export default { name: 'Fridge', data() { return { username: '', fridge: {}, ingredients: [] } }, }

Aquí está el código que recorre los datos de respuesta y agrega el objeto de ingredients y lo almacena en una matriz llamada ingredients . Intenté declarar es un objeto pero no funcionó.

 for (let i = 0; i < res.data["ingredients"].length; i++) { var obj = this.fridge.ingredients[i] for (var key in obj) { var value = obj[key] this.ingredients.push(value) } }
over 4 years ago · Juan Pablo Isaza
2 answers
Answer question

0

Simplemente puede recorrer cada elemento en la key de ingrediente de cada elemento en la matriz de datos y para cada elemento agregar la clave numOf en el objeto de ingredient y eliminar numOf en el elemento principal.

 let data = [ { "id": 3, "owner": "http://localhost:8000/api/v1/users/3/", "ingredients": [ { "ingredient": { "id": 1, "category": "Fruit", "name": "Apple", "calories": 100.0, }, "numOf": 4 }, { "ingredient": { "id": 2, "category": "Vegetable", "name": "Potato", "calories": 10.0, }, "numOf": 3 } ], "total_number": 0 } ]; data[0].ingredients.map((item, index) => { item["ingredient"]["numOf"] = item["numOf"]; delete item["numOf"]; }); console.log(data);

Si quieres ser más dinámico y no ser específico como en el código anterior

puedes proceder así

 data.forEach(dataItem => { dataItem.ingredients.map((item, index) => { item["ingredient"]["numOf"] = item["numOf"]; delete item["numOf"]; }); });
over 4 years ago · Juan Pablo Isaza Report

0

Puede usar 2 bucles para iterar sobre los datos, agregando numOf al ingrediente y luego eliminándolo.

El primer ciclo recorrerá todos los elementos en data , el segundo recorrerá todos los ingredients en ese objeto.

 const data = [ { "id": 3, "owner": "http://localhost:8000/api/v1/users/3/", "ingredients": [ { "ingredient": { "id": 1, "category": "Fruit", "name": "Apple", "calories": 100.0, }, "numOf": 4 }, { "ingredient": { "id": 2, "category": "Vegetable", "name": "Potato", "calories": 10.0, }, "numOf": 3 } ], "total_number": 0 } ] data.forEach((d) => { d.ingredients.forEach((i) => { i.ingredient.numOf = i.numOf delete i.numOf }) }) console.log(data)

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