Javascript 或 lodash 嵌套 JSON 对象转换

Javascript or lodash nested JSON object transformation

如何使嵌套对象为空

如果对象属性具有空值。请检查下面的JSON

我有 JSON 数据如下

[{
    "student": {
        "id": null,
        "name": null
    },
    "children": [{
        "student": null,
        "children": [{
                "student": {
                    "id": 1,
                    "name": "A"
                }
            },
            {
                "student": {
                    "id": null,
                    "name": null
                }
            }
        ]
    }]
}]


我想将其转换为以下输出

Expected

[{
    "student": null,
    "children": [{
        "student": null,
        "children": [{
                "student": {
                    "id": 1,
                    "name": "A"
                }
            },
            {
                "student": null
            }
        ]
    }]
}]

如果值全部为空,您可以使用以下条件“使”值“无效”。

Object.values(obj).every(value => value == null)

我在下面创建了一个基本的递归函数,它遍历对象并检查它是否需要使对象无效。这都是就地完成的,它会修改原始对象。

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; }

这是使用 object-scan

的迭代解决方案

// const objectScan = require('object-scan');

const data = [{ student: { id: null, name: null }, children: [{ student: null, children: [{ student: { id: 1, name: 'A' } }, { student: { id: null, name: null } }] }] }];

const nullify = objectScan(['**(^children$).student'], {
  useArraySelector: false,
  rtn: 'count',
  filterFn: ({ parent, property, value }) => {
    if (
      value instanceof Object
      && !Array.isArray(value)
      && Object.values(value).every((e) => e === null)
    ) {
      parent[property] = null;
      return true;
    }
    return false;
  }
});

console.log(nullify(data));
// => 2

console.log(data);
// => [ { student: null, children: [ { student: null, children: [ { student: { id: 1, name: 'A' } }, { student: null } ] } ] } ]
.as-console-wrapper {max-height: 100% !important; top: 0}
<script src="https://bundle.run/object-scan@14.3.1"></script>

免责声明:我是object-scan

的作者