【发布时间】:2020-10-24 16:36:45
【问题描述】:
我从一个以 JSON 对象形式提供响应的 API 获取数据。
[
{
"id": 48191,
"title": "Apple Crumble Recipe",
"image": "https://spoonacular.com/recipeImages/48191-312x231.jpg",
"imageType": "jpg",
"usedIngredientCount": 1,
"missedIngredientCount": 2,
"missedIngredients": [
{
"id": 4073,
"amount": 35,
"unit": "g",
"unitLong": "grams",
"unitShort": "g",
"aisle": "Milk, Eggs, Other Dairy",
"name": "margarine",
"original": "35 g margarine or butter",
"originalString": "35 g margarine or butter",
"originalName": "margarine or butter",
"metaInformation": [],
"meta": [],
"image": "https://spoonacular.com/cdn/ingredients_100x100/butter-sliced.jpg"
},
{
"id": 8120,
"amount": 35,
"unit": "g",
"unitLong": "grams",
"unitShort": "g",
"aisle": "Cereal",
"name": "rolled oats",
"original": "35 g rolled oats",
"originalString": "35 g rolled oats",
"originalName": "rolled oats",
"metaInformation": [],
"meta": [],
"image": "https://spoonacular.com/cdn/ingredients_100x100/rolled-oats.jpg"
}
],
{...More objects...}
]
我是 node.js 的新手,但我能够很好地提取“id”、“title”和“image”,但我无法提取嵌套在 missIngredients 数组中的数据。
从missedIngredients 数组中,我只想要originalString。
这是我到目前为止所做的:
// recipes is the array that comes from the JSON object
const result = []
recipes.forEach(element => {
result.push({
id: element.id,
title: element.title,
image: element.image,
missedIngredientCount: element.missedIngredientCount,
missedIngredients: [{
originalString: element.missedIngredients.originalString
}] // need to extract data from missed ingredients
})
})
我知道我所做的不会起作用,因为 element.missedIngredients 是一个数组,而不是一个对象,所以我无法访问它上的 originalString。我想做的是这样的:
missedIngredients: {[
originalString: element.missedIngredients[i].originalString
}]
我需要编写嵌套的 for 循环吗?提前致谢!非常感谢您的帮助。
【问题讨论】:
标签: node.js json nested extract