【发布时间】:2021-03-15 12:23:11
【问题描述】:
我有这个猫鼬对象:
recipe = {
"ingredients": [
{
"_id": "5fc8b729c47c6f38b472078a",
"ingredient": {
"unit": "ml",
"name": "olive oil",
"createdAt": "2020-10-09T10:53:35.567Z",
"updatedAt": "2020-12-03T09:25:43.282Z",
"unitConversion": [
{
"_id": "5fc0a688c1799719d03aea3f",
"value": 20,
"convertedValue": 1,
"unitMeasure": {
"name": "spoon",
"createdAt": "2020-11-19T07:31:11.353Z",
"updatedAt": "2020-11-19T07:31:11.353Z",
"id": "5fb61f3f0a62dc27fc052271"
}
}
],
"id": "5f80412f583af20c8c0aeea1"
},
"quantity": 2,
"unitConv": "5fc0a688c1799719d03aea3f"
}
]
}
我想要做的是,用 unitConversion 数组中具有匹配 id 的对象填充 unitConv。
这是我的代码:
const newRecipe = recipe.ingredients.map((ingredient) => {
let unit
if (ingredient.unitConv && ingredient.unitConv !== null) {
unit = ingredient.ingredient.unitConversion.reduce((unit) => {
if (unit.id === ingredient.unitConv) {
return unit
}
})
ingredient.unitConv = unit
}
return ingredient
})
它有效。 ingredient.unitConv 使用来自 unitConversion 数组的匹配 id 的对象填充,但不是对象。它被添加为字符串。
这就是成分.unitConv 的填充方式:
"unitConv": "{\n _id: 5fc0a688c1799719d03aea3f,\n value: 20,\n convertedValue: 1,\n unitMeasure: {\n _id: 5fb61f3f0a62dc27fc052271,\n name: 'spoon',\n createdAt: 2020-11-19T07:31:11.353Z,\n updatedAt: 2020-11-19T07:31:11.353Z,\n }\n}"
我尝试在它上面使用 JSON.parse(),但它不起作用,我会得到几个 SyntaxError 类型的错误(位置的 JSON 中的意外标记...)。我试过 JSON.parse(JSON.stringify('the object')),但这根本不会填充。
【问题讨论】:
标签: javascript node.js json mongoose