如何使用javascript将JSON对象推入数组 [英] How to push JSON object in to array using javascript
本文介绍了如何使用javascript将JSON对象推入数组的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我正在尝试从url获取JSON数据。它是对象的形式我必须将对象数据推送到数组中。
I am trying to fetch the JSON data from an url.It is in the form of object i have to push the object data into array.
var my_json;
$.getJSON("https://api.thingspeak.com/channels/"+did+"/feeds.json?api_key="+apikey+"&results=300", function(json1) {
console.log(json1);
json1.feeds.forEach(function(feed,i){
console.log("\n The details of " + i + "th Object are : \nCreated_at: " + feed.created_at + "\nEntry_id:" + feed.entry_id + "\nField1:" + feed.field1 + "\nField2:" + feed.field2+"\nField3:" + feed.field3);
my_json = feed;
console.log(my_json); //Object {created_at: "2017-03-14T01:00:32Z", entry_id: 33358, field1: "4", field2: "4", field3: "0"}
var data = [];
for(var i in my_json)
data.push(my_json [i]);
console.log(data); //["2017-03-14T01:00:32Z", 33358, "4", "4", "0"]
});
我在my_json var中尝试过如上所示我有对象形式的json数据现在我必须存储该对象以下列格式将数据变为数组
I have tried as above in my_json var i have the json data in the form of object now i have to store that object in to var data as an array in the below format
[{
"created_at": "2017-03-14T01:00:32Z",
"entry_id": 33358,
"field1": "4",
"field2": "4",
"field3": "0"
},
{
"created_at": "2017-03-14T22:54:43Z",
"entry_id": 33398,
"field1": "84",
"field2": "32",
"field3": "0"
}];
任何人都可以帮我怎么做??谢谢你
Can anyone help me how to do it??Thankyou
推荐答案
观察
- 如果有单一对象,你想把整个对象推入一个数组,然后不需要迭代对象。
试试这个:
var feed = {created_at: "2017-03-14T01:00:32Z", entry_id: 33358, field1: "4", field2: "4", field3: "0"};
var data = [];
data.push(feed);
console.log(data);
而不是:
var my_json = {created_at: "2017-03-14T01:00:32Z", entry_id: 33358, field1: "4", field2: "4", field3: "0"};
var data = [];
for(var i in my_json) {
data.push(my_json[i]);
}
console.log(data);
这篇关于如何使用javascript将JSON对象推入数组的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文