Adding two concatenated JSON values in JavaScript

Viewed 52

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
            }
        }
     ]
3 Answers

You're concatenating a string, so 2 is coerced into a string and added to the end of <td>, then 4 is coerced into a string and added to the end of <td>2, etc...

If you want their sum, compute it before it's concatenated.

const wins = 2;
const loss = 4;

console.log('<td>' + wins + loss + '</td>');
console.log('<td>' + (wins + loss) + '</td>');

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>`

This should work:

<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>

Related