我想知道如何添加这个

{ post_id: 1, text: "text", creation: "date" }


像这样的数组中的“帖子”

 var posts = [

    {
        post_id: 5,
        text: "text",
        creation: "date"
    },
    {
        group: "favPosts",
        posts: [
                    { post_id: 2, text: "text", creation: "date" },
                    { post_id: 7, text: "text", creation: "date" }
               ]
    },
    {
        post_id: 8,
        text: "text",
        creation: "date"
    }
]


我已经尝试搜索一百次,但是我似乎找不到适合我的情况的答案,我一直在尝试使用诸如slice和push之类的命令将其插入,但是我似乎无法正确地找到它,仍然是javascript的初学者。

PS:我已经找到了解决方案,但我认为这不是非常“有效”。

addToGroup("favPosts");

function addToGroup(group) {

    for(id in posts) {

        if(posts[id].group == group){

            posts[id].posts.push({ post_id: 10, text: "did it", creation: "date" });

            console.log(posts[id]);
        }
    }
}

最佳答案

这应该可以一推再用,我不明白为什么这不起作用。
这是一个示例,我只是使用angular来轻松地以HTML形式显示,而您所做的事情并不需要:http://plnkr.co/edit/PBCYxfjMqV3jzggMHJZ7?p=preview

var people = [
    {
        name: "Joe",
        surname: "surname"
    },
    {
        group: "name",
        people: [{ name: "name", surname: "surname" }, { name: "name", surname: "surname"     }]
    },
    {
        name: "James",
        surname: "surname"
    }
];

var person = { name: "Jennifer", surname: "surname" };

people.push(person);

关于javascript - 将数据推送到没有索引的数组,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/26472649/

10-11 01:02