简体   繁体   English

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

[英]Traversing nested javascript object to identify empty value properties

If I had an object:如果我有一个对象:

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

And I wanted to get the paths of the properties with undefined values.我想获取具有未定义值的属性的路径。 How could I iterate through all of the properties, including the nested ones?如何遍历所有属性,包括嵌套属性?

Currently, I have this vanilla js method for an object without nested properties:目前,我有一个没有嵌套属性的对象的原生 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.

I'm stuck.我被困住了。 Can someone help out on how to get paths of those undefined values in a nested property of a js object?有人可以帮助了解如何在 js 对象的嵌套属性中获取那些未定义值的路径吗? I'm attempting this in vanilla javascript only.我只在 vanilla javascript 中尝试这个。 Thanks in advance.提前致谢。

You can use recursive function like so:您可以像这样使用递归函数:

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');

This will return an Array of paths to undefined properties这将返回undefined属性的路径Array

You can use join on resulting 'Array' to get String if necessary:如有必要,您可以在结果“数组”上使用 join 来获取String

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

We now use object-scan for data processing like that.我们现在使用对象扫描进行这样的数据处理。 Just so hard to reinvent the wheel every time.每次都很难重新发明轮子。 Here is how it would work这是它的工作方式

 // 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>

Disclaimer : I'm the author of object-scan免责声明:我是对象扫描的作者

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM