BT101
BT101

Reputation: 3826

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]) {
        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.

Upvotes: 1

Views: 330

Answers (1)

jspcal
jspcal

Reputation: 51894

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'
    };
}

Upvotes: 1

Related Questions