作者热门文章
- html - 出于某种原因,IE8 对我的 Sass 文件中继承的 html5 CSS 不友好?
- JMeter 在响应断言中使用 span 标签的问题
- html - 在 :hover and :active? 上具有不同效果的 CSS 动画
- html - 相对于居中的 html 内容固定的 CSS 重复背景?
我想遍历我的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/
我是一名优秀的程序员,十分优秀!