admin管理员组文章数量:1307542
I'm trying to validate a JSON object with node.js. Basically, if condition A is present then I want to make sure that a particular value is in an array which may not be present. I do this in python using dictionary.get because that will return a default value if I look up something that isn't present. This is what it looks like in python
if output.get('conditionA') and not 'conditionB' in output.get('deeply', {}).get('nested', {}).get('array', []):
print "There is an error somewhere you need to be fixing."
I'd like to find a similar technique for javascript. I tried using defaults in underscore to create the keys if they aren't there but I don't think I did it right or I'm not using it the way it was intended.
var temp = _.defaults(output, {'deeply': {'nested': {'array': []}}});
if (temp.hasOwnProperty('conditionA') && temp.deeply.nested.array.indexOf('conditionB') == -1) {
console.log("There is an error somewhere you need to be fixing.");
}
It seems like if it runs into an output where one of the nested objects is missing it doesn't replace it with a default value and instead blows with a TypeError: Cannot read property 'variety' of undefined
where 'variety' is the name of the array I'm looking at.
I'm trying to validate a JSON object with node.js. Basically, if condition A is present then I want to make sure that a particular value is in an array which may not be present. I do this in python using dictionary.get because that will return a default value if I look up something that isn't present. This is what it looks like in python
if output.get('conditionA') and not 'conditionB' in output.get('deeply', {}).get('nested', {}).get('array', []):
print "There is an error somewhere you need to be fixing."
I'd like to find a similar technique for javascript. I tried using defaults in underscore to create the keys if they aren't there but I don't think I did it right or I'm not using it the way it was intended.
var temp = _.defaults(output, {'deeply': {'nested': {'array': []}}});
if (temp.hasOwnProperty('conditionA') && temp.deeply.nested.array.indexOf('conditionB') == -1) {
console.log("There is an error somewhere you need to be fixing.");
}
It seems like if it runs into an output where one of the nested objects is missing it doesn't replace it with a default value and instead blows with a TypeError: Cannot read property 'variety' of undefined
where 'variety' is the name of the array I'm looking at.
-
If you want to approach it this way, you can have "defaults" using the || operator. It will be ugly though:
((((output.deeply || {}).nested || {}).array || []).indexOf...
– Clint Powell Commented Nov 18, 2014 at 21:24
4 Answers
Reset to default 4Or better yet, here's a quick wrapper that imitates the functionality of the python dictionary.
http://jsfiddle/xg6xb87m/4/
function pydict (item) {
if(!(this instanceof pydict)) {
return new pydict(item);
}
var self = this;
self._item = item;
self.get = function(name, def) {
var val = self._item[name];
return new pydict(val === undefined || val === null ? def : val);
};
self.value = function() {
return self._item;
};
return self;
};
// now use it by wrapping your js object
var output = {deeply: { nested: { array: [] } } };
var array = pydict(output).get('deeply', {}).get('nested', {}).get('array', []).value();
Edit
Also, here's a quick and dirty way to do the nested / multiple conditionals:
var output = {deeply: {nested: {array: ['conditionB']}}};
var val = output["deeply"]
if(val && (val = val["nested"]) && (val = val["array"]) && (val.indexOf("conditionB") >= 0)) {
...
}
Edit 2 updated the code based on Bergi's observations.
The standard technique for this in JS is (since your expected objects are all truthy) to use the ||
operator for default values:
if (output.conditionA && (((output.deeply || {}).nested || {}).array || []).indexOf('conditionB') == -1) {
console.log("There is an error somewhere you need to be fixing.")
}
The problem with your use of _.defaults
is that it's not recursive - it doesn't work on deeply nested objects.
If you'd like something that's a little easier to use and understand, try something like this. Season to taste.
function getStructValue( object, propertyExpression, defaultValue ) {
var temp = object;
var propertyList = propertyExpression.split(".");
var isMatch = false;
for( var i=0; i<propertyList.length; ++i ) {
var value = temp[ propertyList[i] ];
if( value ) {
temp = value;
isMatch = true;
}
else {
isMatch = false;
}
}
if( isMatch ) {
return temp;
}
else {
return defaultValue;
}
}
Here's some tests:
var testData = {
apples : {
red: 3,
green: 9,
blue: {
error: "there are no blue apples"
}
}
};
console.log( getStructValue( testData, "apples.red", "No results" ) );
console.log( getStructValue( testData, "apples.blue.error", "No results" ) );
console.log( getStructValue( testData, "apples.blue.error.fail", "No results" ) );
console.log( getStructValue( testData, "apples.blue.moon", "No results" ) );
console.log( getStructValue( testData, "orange.you.glad", "No results" ) );
And the output from the tests:
$ node getStructValue.js
3
there are no blue apples
No results
No results
No results
$
You can check that a key exists easily in javascript by accessing it.
if (output["conditionA"]) {
if(output["deeply"]) {
if(output["deeply"]["nested"]) {
if(output["deeply"]["nested"]["array"]) {
if(output["deeply"]["nested"]["array"].indexOf("conditionB") !== -1) {
return;
}
}
}
}
}
console.error("There is an error somewhere you need to be fixing.");
return;
本文标签: nodejsjavascript equivalent to python39s dictionarygetStack Overflow
版权声明:本文标题:node.js - javascript equivalent to python's dictionary.get - Stack Overflow 内容由网友自发贡献,该文观点仅代表作者本人, 转载请联系作者并注明出处:http://www.betaflare.com/web/1741792355a2397734.html, 本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌抄袭侵权/违法违规的内容,一经查实,本站将立刻删除。
发表评论