1

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]);
        }
    }
}
  • 1
    That isn't valid. You would need to make `people` be an array. `people: [{name: "name", surname: "surname" }, { ... }, ...]` – forgivenson Oct 20 '14 at 18:40
  • 1
    You question would perhaps be clearer if you didn't have `name:"name"` and `surname:"surname"` everywhere. It's really not clear *where* you are trying to insert your value since you seen to have identical objects all over the place. – Matt Burland Oct 20 '14 at 18:42
  • 1
    If you knew or determined the index of the `group` within the outer `collection`, it would be: `collection[indexOfGroup].people.push(person);` "[Access / process (nested) objects, arrays or JSON](http://stackoverflow.com/questions/11922383/access-process-nested-objects-arrays-or-json)" – Jonathan Lonowski Oct 20 '14 at 18:52
  • @forgivenson Sorry it's fixed now, Matt Burland i think i made the array "better" now sorry, Jonathan Lanowski Thanks i'll look into that but i'll see if i can get a solution to my problem as it is now. –  Oct 20 '14 at 19:06

1 Answers1

1

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);
DevVex
  • 143
  • 1
  • 6
  • 1
    Thanks but the data is meant to be pushed to "group: "name", >people<" not the "main" array which you named as people too –  Oct 20 '14 at 19:09