I have been trying to figure out how to merge several JSON strings into one.
My method is this:
if (observations[31]) { // Ignore this.
document.getElementById("ajaxrainmo").textContent = observations[31].imperial.precipTotal + observations[30].imperial.precipTotal + observations[29].imperial.precipTotal + observations[28].imperial.precipTotal + observations[27].imperial.precipTotal + observations[26].imperial.precipTotal + observations[25].imperial.precipTotal + observations[24].imperial.precipTotal + observations[23].imperial.precipTotal + observations[22].imperial.precipTotal + observations[21].imperial.precipTotal + observations[20].imperial.precipTotal + observations[19].imperial.precipTotal + observations[18].imperial.precipTotal + observations[17].imperial.precipTotal + observations[16].imperial.precipTotal + observations[15].imperial.precipTotal + observations[14].imperial.precipTotal + observations[13].imperial.precipTotal + observations[12].imperial.precipTotal + observations[13].imperial.precipTotal + observations[11].imperial.precipTotal + observations[10].imperial.precipTotal + observations[9].imperial.precipTotal + observations[8].imperial.precipTotal + observations[7].imperial.precipTotal + observations[6].imperial.precipTotal + observations[5].imperial.precipTotal + observations[4].imperial.precipTotal + observations[3].imperial.precipTotal + observations[2].imperial.precipTotal + observations[1].imperial.precipTotal + observations[0].imperial.precipTotal + " in"
} // Adding up a bunch of rain totals to one number.
It works.. but it is very confusing and messy.. if there is a faster option avaliable, I could use it. Thanks.
2
Answers
This calls for a loop! You are repeating code a lot, which is bad. You could try this:
I don’t think, you can achieve your goal faster, but you can write readable and maintainable code.
Assuming the array has more elements and you want the first 32:
slice(0, 32)
: take the first 32 elements (you don’t need it, if you take all array elements)map(o => o.imperial.precipTotal)
: map each array element to theprecipTotal
stringreverse()
: reverse the stringsjoin('')
: join the strings to one string without separatorAssuming, I misunderstood your question and
precipTotal
contains numbers that you want to sum up, I would go a similar way.slice(0, 32)
: take the first 32 elements (you don’t need it, if you take all array elements)map(o => o.imperial.precipTotal)
: map each array element to theprecipTotal
stringreduce((acc, el) => acc + el)
: sum up the values