gpt4 book ai didi

javascript - 遍历一个对象,只选择一个特定的字段

转载 作者:行者123 更新时间:2023-11-30 20:45:13 25 4
gpt4 key购买 nike

我想遍历我的input对象,只保留fields键下的数据。

    const input = {
fields: {
title: 'hello',
footer: {
fields: {
title: 'foo',
text: 'bar'
}
}
}
}

const expected = {
title: 'hello',
footer: {
title: 'foo',
text: 'bar'
}

到目前为止,这是我对 clean 函数的实现

function clean(obj) {
Object.keys(obj).map(key => {
if (typeof obj[key] === 'object') {
obj[key] = clean(obj[key])
}
})
}

如何让我的 clean 函数按预期改变输入?

最佳答案

应该这样做:

const input = {
fields: {
title: 'hello',
footer: {
fields: {
title: 'foo',
text: 'bar'
}
}
}
};

function traverse(obj) {
if (typeof obj !== 'object') return obj;
if (obj.fields) return traverse(obj.fields);
for (var i in obj) obj[i] = traverse(obj[i]);
return obj;
}

console.log(traverse(input));

关于javascript - 遍历一个对象,只选择一个特定的字段,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/48788071/

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