将JSON值合并为一个文本

时间:2019-02-16 18:55:56

标签: javascript json

我正在使用此javascript在HTML上显示6小时内的天气预报降雪值。 HTML上的文本显示... 0.25、0.25、0.25、0.35、0.20、0.25,而不是1.55。 JSON结果返回6种不同的降雪预测值,我需要将所有这些值加到一个值中才能显示。

JSON的响应看起来像这样...

{"success":true,"error":null,"response":[{"periods":[{"snowIN":0.25},{"snowIN":0.25},{"snowIN":0.25},{"snowIN":0.35},{"snowIN":0.20},{"snowIN":0.25}]}]}  

JS:

<script type="text/javascript" src="https://cdn.aerisapi.com/sdk/js/latest/aerisweather.min.js">
</script>
<script type="text/javascript">


    window.onload = () => {

        const target = document.getElementById('data-reading');
        const aeris = new AerisWeather('CLIENT_ID', 'CLIENT_SECRET');

        const request = aeris.api().endpoint('forecasts').place('pierre,sd').filter('1hr').limit('48');
        request.get().then((result) => {
            const data = result.data;
            const { periods } = data[0];
            if (periods) {
                periods.reverse().forEach(period => {
                    const snowIN = period.snowIN || '0.00';

                    const html = (`
                                 <p class="map-datavalue">${snowIN}"</p>
                            `);

                    target.insertAdjacentHTML('afterbegin', html);
                });
            }
        }); 
    }

</script>

4 个答案:

答案 0 :(得分:0)

您没有将这些值加在一起。

您可以保留一个变量以存储超出for范围的值并添加到其中,然后只需添加该元素即可。

const request = aeris.api().endpoint('forecasts').place('pierre,sd').filter('1hr').limit('48');
var valueToAddToTML = 0;

request.get().then((result) => {
    const data = result.data;
    const { periods } = data[0];
    if (periods) {
        periods.reverse().forEach(period => {
            const snowIN = period.snowIN || '0.00';
            valueToAddToTML += snowIN;

        });
        // Add to HTML
        const html = (`<p class="map-datavalue">${valueToAddToTML}"</p>`);
        target.insertAdjacentHTML('afterbegin', html);
    }
}); 

答案 1 :(得分:0)

您可以使用Array.reduce计算期间的总数:

const target = document.getElementById('data-reading');

const result = {"success":true,"error":null,"response":[{"periods":[{"snowIN":0.25},{"snowIN":0.25},{"snowIN":0.25},{"snowIN":0.35},{"snowIN":0.20},{"snowIN":0.25}]}]} 

const data = result.response;
const { periods } = data[0];
if (periods) {
  const total = periods.reduce((sum, { snowIN }) => sum + snowIN, 0);
  const html = `<p class="map-datavalue">${total || '0.00'}</p>`;
  target.insertAdjacentHTML('afterbegin', html);
}
.map-datavalue { 
  font-family: "Arial",sans-serif;
  font-size: 20px;
  color: #FFFFFF;
  font-weight: 700;
  text-shadow: -2px 0 #000000, 0 2px #000000, 2px 0 #000000, 0 -2px #000000;
  z-index: 6;
}
<div class="map-datavalue" id="data-reading" style="position: absolute; left: 181px; top: 56px; width:76px; height:30px">&nbsp;</div>

只需将其插入您的if (periods) { ... }中,就像这样:

request.get().then((result) => {
    const data = result.data;
    const { periods } = data[0];
    if (periods) {
        const total = periods.reduce((sum, { snowIN }) => sum + snowIN, 0);
        const html = `<p class="map-datavalue">${total || '0.00'}</p>`;
        target.insertAdjacentHTML('afterbegin', html);
    }
}); 

关于此:

const total = periods.reduce((sum, { snowIN }) => sum + snowIn, 0);

等效于此:

let total = 0;
for (let i = 0; i < periods.length; ++i) {
    total += periods[i].snowIN;
}

但是使用解构来获取snowIN属性,并使用reduce来抽象for循环。

答案 2 :(得分:0)

要计算snowIn的总和,只需使用reduce(),这将为您提供一线解决方案,如sum

所述
const result = {"success":true,"error":null,"response":[{"periods":[{"snowIN":0.25},{"snowIN":0.25},{"snowIN":0.25},{"snowIN":0.35},{"snowIN":0.20},{"snowIN":0.25}]}]}  

const sum = res['response'][0]['periods'].reduce((a, b) =>a + b['snowIN'], 0);

console.log(sum)

答案 3 :(得分:0)

在添加到html之前,您可以将所有snowIN合并为一个值。

let obj = {"success":true,"error":null,"response":[{"periods":[{"snowIN":0.25},{"snowIN":0.25},{"snowIN":0.25},{"snowIN":0.35},{"snowIN":0.20},{"snowIN":0.25}]}]} 

let op = obj.response[0].periods.reduce((out,{snowIN})=>out+snowIN,0)

document.getElementById('text').innerHTML = op
//console.log(op)
#text{ color: green; width: 100px; height: 100px;}
<div id='text'>