Search code examples
javascriptjsonsumconcatenationaddition

Adding two concatenated JSON values in JavaScript


Trying to sum two concatenated values from a JSON file and add them to HTML Table:

I'm struggling to wrap my head around how to add value.name.wins with value.name.loss and get a total to show up in the HTML table td slot. They are numbers in the JSON file but are just adding them up to say 24 when it should read 6. Would an entire new function be needed to make this sum happen?

<script>
    $(document).ready(function(){
    $.getJSON("managers.json", function(data) {
        var managers_data = "";
        $.each(data, function(key, value) {
            managers_data += "<tr class='test'>";
            managers_data += '<td>' + value.name.wins+ +value.name.loss+ '</td>';
            });
            $('#managers_table').append(managers_data);
        });
    });
</script>
    [
        {
            "name" : {
                "wins": 2,
                "loss": 4
            }
        }
     ]

Solution

  • Use parentheses: Instead of

    '<td>' + value.name.wins+ +value.name.loss+ '</td>'
    

    Do:

    '<td>' + ((+value.name.wins)+(+value.name.loss))+ '</td>'
    

    Or Simply Template literals:

    `<td>${(+value.name.wins)+(+value.name.loss)}</td>`