我嵌套了像波紋管這樣的對像數組:
const data = [
{text: 'node 1'},
{text: 'node 2', chapter_playlist: [{text: 'node 2-1', lesson_playlist: [{text: 'node 3-1'}]}]},
{text: 'node 3'},
{text: 'node 4', chapter_playlist: [{ text: 'node 4-1' }]}
]
如何將每個嵌套屬性(如chapter_playlist、lesson_playlist)重命名為“ children ”?
基本上我想改變有更多孩子的財產的名字,如果沒有孩子那麼就沒有必要改變它。我仍然困惑如何改變它
預期成績
const data = [
{text: 'node 1'},
{text: 'node 2', children: [{text: 'node 2-1', children: [{text: 'node 3-1'}]}]},
{text: 'node 3'},
{text: 'node 4', children: [{ text: 'node 4-1' }]}
]
有趣的事實:如果您出於某種原因需要遍歷一個對象,JSON.stringify()是您的朋友。
不是因為您想將數據轉換為 JSON 字符串,而是因為它也是一個對象迭代器,可讓您使用替換函數在每個級別執行任意處理:
const data = [
{text: 'node 1'},
{text: 'node 2', chapter_playlist: [{text: 'node 2-1', lesson_playlist: [{text: 'node 3-1'}]}]},
{text: 'node 3'},
{text: 'node 4', chapter_playlist: [{ text: 'node 4-1' }]}
]
const rewriteList = [`chapter_playlist`, `lesson_playlist`];
function replacer(key, value) {
// If the value at this depth is an object (but not an iterable
// like array or Set or Map), then rebind the properties you
// need rebound, provided they exist:
if (typeof value === `object` && !value[Symbol.iterator]) {
rewriteList.forEach(prop => {
if (value[prop]) {
// By editing "value", we're directly updating "data".
value.children = value[prop];
delete value[prop];
}
});
}
return value;
}
JSON.stringify(data, replacer);
console.log(data)
本文收集自互联网,转载请注明来源。
如有侵权,请联系 [email protected] 删除。
我来说两句