遍历嵌套 javascript 对象识别空值属性

Traversing nested javascript object to identify empty value properties

如果我有对象:

var dog= {
  name: "Max",
  age: 5,
  sex: undefined,
  details: {
    color: "black",
    breed: undefined
  }
}

而且我想获取具有未定义值的属性的路径。我如何遍历所有属性,包括嵌套属性?

目前,我有一个没有嵌套属性的对象的 vanilla js 方法:

function getUndefinedPaths(o, name) {
  var paths = [];
  for (var prop in o) {
    if (o[prop] === undefined) {
        paths += name + "." + prop + "\n";
    }
  }
  return paths;
}

// getUndefinedPaths(dog, "dog") only returns "dog.sex" and not "dog.details.breed" which is also undefined.

我卡住了。有人可以帮忙解决如何在 js 对象的嵌套 属性 中获取那些未定义值的路径吗?我仅在香草 javascript 中尝试这样做。提前致谢。

你可以像这样使用递归函数:

function getPath(obj, path) {

    var props = [];    

    for(var key in obj) {

        if(obj[key] === undefined) {
            props.push(path + '.' + key);
        }

        if(obj[key] instanceof Object) {
            props.push.apply(props, getPath( obj[key], path + '.' + key ));
        }

    }

    return props;
}


var path = getPath(dog, 'dog');

这将 return 到 undefined 属性的 Array 路径

如有必要,您可以对结果 'Array' 使用联接以获得 String

console.log(path.join('\n'));

我们现在使用 object-scan 进行这样的数据处理。每次都很难重新发明轮子。这是它的工作原理

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

const find = (data) => objectScan(['**'], {
  joined: true,
  filterFn: ({ value }) => value === undefined
})(data);

const dog = { name: 'Max', age: 5, sex: undefined, details: { color: 'black', breed: undefined } };

console.log(find(dog));
// => [ 'details.breed', 'sex' ]
.as-console-wrapper {max-height: 100% !important; top: 0}
<script src="https://bundle.run/object-scan@13.8.0"></script>

免责声明:我是object-scan

的作者