简体   繁体   中英

Push data to array without index

I'd like to know how can i add this

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

to the "posts" in a array like this

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

I've already tried searching a hundred times but i can't seem to find a answer that suits my case, I've been trying to insert it with commands like slice and push but i can't seem to get it right, i'm still a beginner in javascript.

PS: I've come a solution but i don't think it's very "efficient";

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

This should work with a push, I don't see why this wouldn't work. Here is an example, I just used angular to easily display in HTML, not needed for what you are doing: 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);

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM