這是有問題的資料:
[
{
"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
}
]
我想連接numOf到 hist 父級ingredient以使我的表正確呈現現在給定 2 種成分,我的表有 4 行
編輯
所需的結果應如下所示:
[
{
"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
}
]
您看到的 JSON 檔案是我在查詢用戶冰箱時的服務器回應。然后我想在一張桌子上顯示他所有的成分。這是我在 VueJS 中宣告陣列的方式:
import axios from 'axios'
export default {
name: 'Fridge',
data() {
return {
username: '',
fridge: {},
ingredients: []
}
},
}
這是回圈回應資料并添加ingredients物件并將其存盤在名為的陣列中的代碼ingredients。我試過宣告是一個物件,但它沒有用。
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)
}
}
uj5u.com熱心網友回復:
您可以遍歷key資料陣列中每個專案的成分中的每個專案,并為每個專案添加物件中的numOf鍵ingredient并洗掉numOf父專案上的鍵。
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);
如果您想更加動態并且不像前面的代碼那樣具體
你可以這樣處理
data.forEach(dataItem => {
dataItem.ingredients.map((item, index) => {
item["ingredient"]["numOf"] = item["numOf"];
delete item["numOf"];
});
});
uj5u.com熱心網友回復:
您可以使用 2 個回圈來迭代資料,將其添加numOf到成分中,然后將其洗掉。
第一個回圈將遍歷 中的所有項data,第二個回圈遍歷ingredients該物件中的所有項。
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)
轉載請註明出處,本文鏈接:https://www.uj5u.com/gongcheng/405650.html
標籤:
上一篇:回圈檔案對
