gpt4 book ai didi

javascript - 递归地向数组中的每个对象添加相同的元素

转载 作者:行者123 更新时间:2023-11-30 10:28:03 25 4
gpt4 key购买 nike

我让这个对象包含对象数组(“页面”)

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 我一直在修改函数,但它还不起作用,所以我需要帮助。谢谢。

最佳答案

更改为使用 for 循环而不是 for-in - 对数组更安全。

试试这个:

function add_slug(array_of_obj)
{
for(var pageIdx = 0; pageIdx < array_of_obj.length; ++pageIdx) {
var curPage = array_of_obj[pageIdx];

if(curPage.title) {
curPage.slug = curPage.title.split(' ').join('-');
}

if(curPage.sub) {
add_slug(curPage.sub);
}
}
}

结果:

{
"pages": [
{
"title": "title one",
"sub": [
{
"title": "title one one",
"slug": "title-one-one"
},
{
"title": "title one two",
"slug": "title-one-two"
}
],
"slug": "title-one"
},
{
"title": "title two",
"slug": "title-two"
},
{
"title": "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"
}
],
"slug": "title-three"
}
]
}

关于javascript - 递归地向数组中的每个对象添加相同的元素,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/18603732/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com