搜尋

首頁  >  問答  >  主體

資料結構 - javascript如何將一個個json資料合併成一個物件數組?

{"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"}]

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

迷茫迷茫2736 天前792

全部回覆(4)我來回復

  • 迷茫

    迷茫2017-05-19 10:13:19

    回覆
    0
  • 仅有的幸福

    仅有的幸福2017-05-19 10:13:19

    雷雷

    回覆
    0
  • 巴扎黑

    巴扎黑2017-05-19 10:13:19

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

    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));

    回覆
    0
  • 天蓬老师

    天蓬老师2017-05-19 10:13:19

    你的意思是:
    將後端傳來的.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();

    回覆
    0
  • 取消回覆