【问题标题】:how to make an array from json array如何从json数组创建一个数组
【发布时间】:2018-03-17 16:14:54
【问题描述】:

我有一个这样的 json 响应,

"meteo_inverter_analysis":{  
    "Id93922.1":{  
        "inverter_id":"Id93922.1", "total_electricity_generated":1567.7910000000002
    },
    "Id93922.2":{  
        "inverter_id":"Id93922.2", "total_electricity_generated":1468.4869999999999
    },
    "Id93922.3":{  
        "inverter_id":"Id93922.3","total_electricity_generated":498.7319999999999
    },
    "Id93922.4":{  
        "inverter_id":"Id93922.4","total_electricity_generated":461.8369999999999
    }

}

从该响应中,我想从 total_electricity_generated 创建一个 js 数组。该数组将是: var 数组 = [1567.7910000000002, 1468.4869999999999, 498.7319999999999, 461.8369999999999]

谁能帮我怎么做? TIA

【问题讨论】:

标签: javascript json


【解决方案1】:

我认为下面的例子会对你有所帮助:

 <script>
  var car =new Array();
  var myObj, i;
  myObj = {
 "name":"John",
 "age":30,
 "cars":[ "Ford", "BMW", "Fiat" ]
 };

 for (i = 0; i < myObj.cars.length; i++) {
 car[i]= myObj.cars[i] + "<br>";
 }

</script>

【讨论】:

    【解决方案2】:

    您可以获取meteo_inverter_analysis 的键,然后循环到该键以获取Id93922.* 的属性值

    var data = {"meteo_inverter_analysis":{  
        "Id93922.1":{  
            "inverter_id":"Id93922.1",     
             "total_electricity_generated":1567.7910000000002
        },
        "Id93922.2":{  
            "inverter_id":"Id93922.2",
            "total_electricity_generated":1468.4869999999999
        },
        "Id93922.3":{  
            "inverter_id":"Id93922.3",
            "total_electricity_generated":498.7319999999999
        },
        "Id93922.4":{  
            "inverter_id":"Id93922.4",
            "total_electricity_generated":461.8369999999999
        }
    }
    };
    
    var keys = Object.keys(data.meteo_inverter_analysis);
    var arr = keys.map(key => data.meteo_inverter_analysis[key].total_electricity_generated
    );
    
    console.log(arr);

    【讨论】:

    • 这就是我需要的答案,谢谢@Ankit Agarwal
    猜你喜欢
    • 2013-06-11
    • 1970-01-01
    • 2023-03-19
    • 1970-01-01
    • 1970-01-01
    • 2017-03-17
    • 2021-12-24
    • 1970-01-01
    • 2018-04-19
    相关资源
    最近更新 更多