Add to object instead of overwrite it

问题: I'm using following code $scope.createAuction = function () { var auction = { auction: { langData: {} } }; if($scope.selected.tab === $scope.infoTabs[0]) {...

问题:

I'm using following code

$scope.createAuction = function () {
    var auction = { auction: { langData: {} } };

    if($scope.selected.tab === $scope.infoTabs[0]) {
        Object.assign(auction.auction, {
          type: 'account',
          layout: $scope.selected.description
        });
        if(auction.auction.layout === 1) {
            for(var i = 0, l = $scope.langInput.values.length; i < l; i++) {
                auction.auction.langData[$scope.langInput.values[i].selected] = {
                    name: $scope.inputs.auction_name_account[i + 1]
                };
            }
            for(var i = 0, l = $scope.langInput.values.length; i < l; i++) {
                auction.auction.langData[$scope.langInput.values[i].selected] = {
                    description: 'a'
                }
            }
        }
    }
    console.log(JSON.stringify(auction));
}

in order to add to values to object which are provided by user. I'm using loop because user can change count of inputs.

What I want to achieve is that my object will look like this:

"auction": {
    "type": "car",
    "layout": 1,
    "langData": {
        "pl": {
            "name": "nazwa aukcji w pl",
            "description": "opis aukcji w pl",
        },
        "eng": {
            "name": "name auction eng",
            "description": "description auction eng",
        },

But my code is overwriting "pl" and "eng" so result is that I see only description.


回答1:

In the second loop, insert the description property rather than overwriting the object:

for(var i = 0, l = $scope.langInput.values.length; i < l; i++) {
    auction.auction.langData[$scope.langInput.values[i].selected].description = 'a';
}

You can also combine the loops if you so choose:

for (var i = 0, l = $scope.langInput.values.length; i < l; i++) {
    auction.auction.langData[$scope.langInput.values[i].selected] = {
        name: $scope.inputs.auction_name_account[i + 1],
        description: 'a'
    };
}
  • 发表于 2018-07-06 02:11
  • 阅读 ( 90 )
  • 分类:sof

条评论

请先 登录 后评论
不写代码的码农
小编

篇文章

作家榜 »

  1. 小编 文章
返回顶部
部分文章转自于网络,若有侵权请联系我们删除