javascript - Javascript or lodash nested JSON object transformation
问题描述
How to make nested object null
if object attributes has a null values. please check the JSON below
I have JSON data as following
[{
"student": {
"id": null,
"name": null
},
"children": [{
"student": null,
"children": [{
"student": {
"id": 1,
"name": "A"
}
},
{
"student": {
"id": null,
"name": null
}
}
]
}]
}]
I want to convert it to following output
Expected
[{
"student": null,
"children": [{
"student": null,
"children": [{
"student": {
"id": 1,
"name": "A"
}
},
{
"student": null
}
]
}]
}]
解决方案
You could "nullify" values if their values are all null using the following conditional.
Object.values(obj).every(value => value == null)
I created a basic recursive function to below that traverses the object and checks to see if it needs to nullify an object. This is all done in-place, and it will modify the original object.
const obj = [{
"student": { "id": null, "name": null },
"children": [{
"student": null,
"children": [
{ "student": { "id": 1, "name": "A" } },
{ "student": { "id": null, "name": null } }
]
}]
}];
const nullify = (obj, key = null, parent = null) => {
if (obj != null) {
if (Array.isArray(obj)) {
obj.forEach((item, index) => nullify(item, index, obj));
} else if (typeof obj === 'object') {
if (Object.values(obj).every(value => value == null)) {
parent[key] = null;
} else {
Object.entries(obj).forEach(([key, value]) => nullify(value, key, obj));
}
}
}
};
nullify(obj);
console.log(obj);
.as-console-wrapper { top: 0; max-height: 100% !important; }
推荐阅读
- apache-kafka - 在 Docker 环境中启动分布式 Kafka 连接后创建 Kafka 连接器
- javascript - useState 根本不更新数组
- amazon-web-services - 为什么 CDK 抱怨缺少公共子网组?
- java - 无法使用 Java 实现 Stack
- python-3.x - 条形图中不需要的间距
- python - 这个 python 代码有多安全,我应该运行它吗
- sql - Sql:合并具有相同id和多个属性的行
- sql - Postgresql:使用另一列的值更新文本列
- c# - 如何在 C# 中使用多线程进行批处理
- c# - 我怎样才能最好地在我的 WPF 应用程序中实现异步?