数据结构 - javascript如何将一个个json数据合并成一个对象数组?
迷茫
迷茫 2017-05-19 10:11:19
0
4
797

{"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();
热门教程
更多>
最新下载
更多>
网站特效
网站源码
网站素材
前端模板