資料結構 - javascript如何將一個個json資料合併成一個物件數組?
迷茫
迷茫 2017-05-19 10:11:19
0
4
805

{"name":"`111","password":"111","title":"111","tag":"111","contents":"1111"},{ "name":"222","password":"22","title":"22","tag":"22","contents":"222"},{"name":"11", "password":"11","title":"11","tag":"11","contents":"11111"}

#轉化為

[{"name":"`111","password":"111","title":"111","tag":"111","contents":"1111"}, {"name":"222","password":"22","title":"22","tag":"22","contents":"222"},{"name":"11" ,"password":"11","title":"11","tag":"11","contents":"11111"}]

補充一下,這是從後台傳到前端的資料

迷茫
迷茫

业精于勤,荒于嬉;行成于思,毁于随。

全部回覆(4)
巴扎黑

完善了一下下樓的程式碼,得到了樓主想要的效果

var obj = {
    a: {"name": "111", "password": "111", "title": "111", "tag": "111", "contents": "1111"},
    b: {"name": "222", "password": "22", "title": "22", "tag": "22", "contents": "222"},
    c: {"name": "11", "password": "11", "title": "11", "tag": "11", "contents": "11111"}
};
var result = [];
for (var key in obj) {
    result.push(obj[key]);
}
console.log(JSON.stringify(result));

Peter_Zhu

你的意思是:
將後端傳來的.json檔案中的數據,放到前端新的物件陣列裡吧。
傳的話是需要ajax的(例子是jquery的ajax方法),你也可以試試現在比較流行的axios。

假設:
1.需要傳入的檔案是test.json
2.test.json的資料內容是

{
    "userone":{"name":"111","password":"111","title":"111","tag":"111","contents":"1111"},
    "usertwo":{"name":"222","password":"22","title":"22","tag":"22","contents":"222"},
    "userthree":{"name":"11","password":"11","title":"11","tag":"11","contents":"11111"}
}

轉換:
1.透過ajax取得到數據,所獲得的內容存在了data中
2.遍歷json資料並存到新的物件數組中,在success函數中進行

function getJson(){
        $.ajax({
            type:"GET",
            url:"test.json",
            dataType:"json",
            success:function(data){
                var jsonData=data;
                var newObject=[];
                for (var key in jsonData) {
                    newObject.push(jsonData[key])
                }
                JSON.stringify(newObject);
                console.log(newObject);
            }
        })
}
getJson();
熱門教學
更多>
最新下載
更多>
網站特效
網站源碼
網站素材
前端模板