我有这个对象包含对象数组('pages')
var obj = {
"pages" : [
{
"title": "title one",
"sub" : [
{ "title" : "title one one"},
{ "title" : "title one two"}
]
},
{ "title" : "title two" },
{
"title" : "title three",
"sub" : [
{ "title" : "title three one"},
{ "title" : "title three two"},
{ "title" : "title three three"}
]
}
]
}
和这样的预期结果(将“slug”元素添加到“页面”中的每个对象)
{
"pages" : [
{
"title" : "title one",
"slug" : "title-one",
"sub" : [
{
"title" : "title one one",
"slug" : "title-one-one"
},
{
"title" : "title one two",
"slug" : "title-one-two"
}
]
},
{
"title" : "title two",
"slug" : "title-two"
},
{
"title" : "title three",
"slug" : "title-three",
"sub" : [
{
"title" : "title three one",
"slug" : "title-three-one"
},
{
"title" : "title three two",
"slug" : "title-three-two"
},
{
"title" : "title three three",
"slug" : "title-three-three"
}
]
}
]
}
我想我可以做到
function add_slug(array_of_obj)
{
for (var item in array_of_obj) {
//i am not sure about this:
item.slug = item.title.replace(/ /g, '-');
if(typeof item.sub !== undefined) {
add_slug(item.sub);
}
}
}
add_slug(obj.pages);
但是我得到undefined item.title
我一直在修改函数但它还不起作用所以我需要帮助。谢谢。