我有一个看起来像这样的对象:
var ingredientsObject = {
"Ingredients": [
{ "Section": "Ingredienser", "Name": "salt", "Value": 1, "Unit": "tsk" },
{ "Section": "Ingredienser", "Name": "olivolja", "Value": 1, "Unit": "msk" },
{ "Section": "Ingredienser", "Name": "lasagneplattor, (125 g) färska", "Value": 6, "Unit": "st" },
{ "Section": "Tomatsås", "Name": "salt", "Value": 0.5, "Unit": "tsk" },
{ "Section": "Tomatsås", "Name": "strösocker", "Value": 2, "Unit": "krm" }
{ "Section": "Béchamelsås", "Name": "salt", "Value": 0.5, "Unit": "tsk" },
{ "Section": "Béchamelsås", "Name": "smör", "Value": 2.5, "Unit": "msk" }
]
};
我试图根据使用下划线指定的份数重新计算每种成分的价值。
我尝试过使用mapObject(http://underscorejs.org/#mapObject):
newIngredients = _.mapObject(ingredients.Ingredients, function (val, key) {
return val.Value / modifier;
});
但是返回一个如下所示的对象:
Object {0: 0.3333333333333333, 1: 0.3333333333333333, 2: 2, 3: 0.3333333333333333, 4: 50, 5: 66.66666666666667, 6: 0.16666666666666666, 7: 0.6666666666666666, 8: 0.25, 9: 0.3333333333333333, 10: 0.3333333333333333, 11: 0.16666666666666666, 12: 0.8333333333333334, 13: 0.16666666666666666, 14: 0.8333333333333334, 15: 1.6666666666666667, 16: 0.6666666666666666}
而我真正想要的只是改变了值的原始对象,如:
var ingredientsObject = {
"Ingredients": [
{ "Section": "Ingredienser", "Name": "salt", "Value": 0.3333333333333333, "Unit": "tsk" },
{ "Section": "Ingredienser", "Name": "olivolja", "Value": 0.3333333333333333, "Unit": "msk" },
{ "Section": "Ingredienser", "Name": "lasagneplattor, (125 g) färska", "Value": 2, "Unit": "st" }
// and so on...
]
};
我如何实现这一目标?
答案 0 :(得分:0)
尝试:
newIngredients = _.map(ingredientsObject.Ingredients, function(item) {
return {
Section: item.Section,
Name: item.Name,
Value: item.Value / modifier,
Unit: item.Unit
};
});
答案 1 :(得分:0)
实际上tr
是一个数组,ingredients.Ingredients
期望一个对象作为第一个参数。您可以采用下划线方式执行此操作:
_.mapObejct
答案 2 :(得分:0)
好的,根据我收到的意见和建议,我提出了这个解决方案:
newIngredients = _.each(ingredientsObject, function (list) {
_.each(list, function (item) {
item.Value = item.Value / modifier;
});
});
这会在不修改对象结构的情况下修改值本身。
感谢@nnnnnn指出我正确的方向。