上保留键我有一个对象,看起来像这样:下划线不是嵌套对象
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...
]
};
我该如何做到这一点?
鉴于你根本不想改变对象的*结构*,你只是想改变每个项目的''Value''属性*为什么不使用'forEach ()循环''val.Value = val.Value/modifier;'? – nnnnnn