簡體   English   中英

下划線不保留嵌套對象上的鍵

[英]underscore not retaining keys on nested object

我有一個看起來像這樣的對象:

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...
    ]
};

我該如何實現?

嘗試:

 newIngredients = _.map(ingredientsObject.Ingredients, function(item) {
    return { 
      Section: item.Section,
      Name: item.Name,
      Value: item.Value / modifier,
      Unit: item.Unit
    };
});

實際上ingredients.Ingredients是一個數組, _.mapObejct期望對象作為第一個參數。 您可以通過下划線方式執行此操作:

_.mapObject(ingredientsObject, function(val, key) {
    return _.map(val, function(ingredient) {
        return _.extend(
          {},
          ingredient,
          {
            Value: ingredient.Value / modifier
          }
        )
    })
})

好的,根據收到的評論和建議,我提出了以下解決方案:

newIngredients = _.each(ingredientsObject, function (list) {
    _.each(list, function (item) {
        item.Value = item.Value / modifier;
    });
});

這將修改值本身,而無需修改對象結構。

感謝@nnnnnn為我指出正確的方向。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM