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) } }
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"]; }); });
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)