gpt4 book ai didi

javascript - 对象分配删除一些属性然后创建新对象

转载 作者:行者123 更新时间:2023-12-03 03:40:47 26 4
gpt4 key购买 nike

尝试从对象中删除不必要的属性:

{
"1502134857307": {
"bio": "",
"category": {
"category1": true
},
"name": "dog",
"snapchat": "",
"twitter": ""
},
"1502134908057": {
...
}
}

我想让它看起来像这样:

{
"1502134857307": {
"category": {
"category1": true
},
"name": "dog"
},
"1502134908057": {
...
}
}

我已经尝试过:不起作用

var newObejct = Object.assign({}, $r.props.data);
delete newObejct.bio;

最佳答案

来,试试这个。根据您想要完成的任务,这将递归地迭代嵌套对象并删除任何空字符串属性。请随意修改条件以删除对象中不需要的任何其他内容。

let clutteredObj = {
"1502134857307": {
"bio": "",
"category": {
"category1": true
},
"name": "dog",
"snapchat": "",
"twitter": ""
},
"1502134908057": {
"bio": "",
"category": {
"category1": true
},
"name": "dog",
"snapchat": "",
"twitter": ""
}
}

function clearEmptyStrings(obj) {
Object.keys(obj).forEach(key => {
if (typeof obj[key] === 'object') {
return clearEmptyStrings(obj[key])
}
if (obj[key] === "") {
delete obj[key]
}
})
}

clearEmptyStrings(clutteredObj);

console.log(clutteredObj)

关于javascript - 对象分配删除一些属性然后创建新对象,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/45639113/

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