javascript如何将一个个json数据合并成一个对象数组?

发布于 2022-09-04 22:10:10 字数 556 浏览 21 评论 0

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

补充一下,这是从后台传到前端的数据

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(4

高速公鹿 2022-09-11 22:10:10
// 把数据往里面一扔
var tx = {
    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 sb = [];
// 遍历栈入
for (var tb in tx) {
    sb.push(tx[tb])
}
console.log(sb[]);
染柒℉ 2022-09-11 22:10:10

完善了一下下楼上的代码,得到了楼主想要的效果

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

图片描述

闻呓 2022-09-11 22:10:10

你的意思是:
将后端传来的.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();
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文