我想知道如何添加此
{ 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"
}
]
我已经尝试了一百次搜索,但我似乎无法找到适合我的情况的答案,我一直试图插入像切片和推送这样的命令,但我可以& #39; t似乎做对了,我还是javascript的初学者。
PS:我已经找到了解决方案,但我认为它不是非常有效的,并且#34 ;;
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]);
}
}
}
答案 0 :(得分:0)
这应该是推动,我不明白为什么这不会起作用。 这是一个例子,我只是使用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);