用于解析不同参数的对象的Javascript泛型方法

时间:2017-06-20 13:42:41

标签: javascript angular typescript ecmascript-6 javascript-objects

var data = {
  'id': 'object1',
  'sceneCapability': {
  'updatedAt': '2017-06-19T20:52:45.688Z'
    'currentScene': {
      'value': {
        'number': 1,
        'name': '1'
      }
    },
    'outOfTune': {
      'value': false
    }
  },

  'lightingCapability': {
    'intensity': {
      'value': 0
    }
  },

  'tiltCapability': {
    'command': {
      'value': 'NO'
    },
    'position': {
      'value': 0
    }
  }

// like this I have different types of more than 20 Capabilities 
};

如何编写通用方法来解析此Object?我需要获得currentScene值,outOfTuneintensitycommandposition等等。

有时我只获得一项功能,有时我获得了20多项功能。

我想避免做这样的事情,因为将来可能有数百种不同的功能

if (obj.lightingCapability && obj.lightingCapability.intensity) {
        console.log(obj.lightingCapability.intensity.value)
}

if (device.sceneCapability && device.sceneCapability.outOfTune) {
            // do something
        }

输出我想要

currentScene:1,
outOfTune: false,
intensity: 0,
command: 'NO',
position: 0

5 个答案:

答案 0 :(得分:4)

这样的事情对你有用吗?

一个辅助函数,它找到你需要的属性,如果链上的任何东西都不存在,则返回null。我添加了两个不同的'版本,以防你不喜欢属性名称数组。

var object = {
    a: {
        b: {
            c: {
                d: 10
            }
        }
    }
};

function getValue(object, propertyPath) {
    var o = object;
    var pLen = propertyPath.length;

    for (var i = 0; i < pLen; i++) {
        var propertyName = propertyPath[i];
        if (!o.hasOwnProperty(propertyName))
            return undefined;

        o = o[propertyName];
    }

    return o;
}

function getValueFromString(object, path) {
    return this.getValue(object, path.split('.'));
}

console.log(getValue(object, ['a', 'b', 'c', 'd']));    //logs 10
console.log(getValueFromString(object, 'a.b.c.d'));     //logs 10
console.log(getValue(object, ['a', 'b', 'c', 'e']));    //logs undefined

答案 1 :(得分:3)

根据我在第一个回答的评论中的讨论,我意识到你的意思不同。这应该可以解决问题:

var object = {
    a: {
        b: {
            c: {
                value: 10
            },
            d: {
                e: {
                    value: 20
                }
            }
        }
    }
};

function logAllValues(object) {
    for (var p in object) {
        var o = object[p];
        if (o.value)
            console.log(p + ': ' + o.value);
        else 
            logAllValues(o);
    }
}

logAllValues(object);    //logs c:10 and e:20

答案 2 :(得分:1)

执行此操作的一种稍微晦涩的方法是创建一个帮助函数,该函数允许将键链作为字符串传递并在其上循环。例如

function getValue(obj, keyChain){
  var keys = keyChain.split('.');
  do {
    var key = keys.shift();
    if (!obj.hasOwnProperty(key)){
      return undefined;
    }
    obj = obj[key];
  } while (keys.length > 0);
  return obj;
}

getValue(data, "lightingCapability.intensity.value")

答案 3 :(得分:0)

我认为您只需要安装lodash#get

  

npm i --save lodash.get

var get = require('lodash.get');

if(get('foo.baz.foobaz')) {
  alert('yep');
}

但您需要事先了解所需的所有paths

重新实施这种经过社区测试的方法将最终重新发明轮子,所以,只需安装并使用它。

答案 4 :(得分:-1)

你可以使用ES6 try和catch block来实现这样的东西

bcrypt.genSalt(10, function(err,salt){
    if (err){ 
        return console.log('error in hashing the password');
    } 
    bcrypt.hash(pass, salt, function(err,hash){
        if (err){
            return console.log('error in hashing #2');
        } else {

            console.log('hash of the password is ' + hash);
            console.log(pass);
            storehash = hash; 
            console.log(storehash);
            db.create({

                email: req.body.email,
                username: req.body.username,
                password: storehash,


            }, function(err, User){
                if (err){ 
                    console.log('error in creating user with authentication');
                } else {
                    console.log('user created with authentication');
                    console.log(User);
                }
            }); //db.create
        }
    });

}); 

//像这样使用

getValue(()=&gt; object.a.b); //返回Object {c:Object,d:Object}

getValue(()=&gt; object.a.b.c); //返回Object {value:10}

getValue(()=&gt; object.a.b.x); //返回undefined

相关问题