如何在对象中搜索特定的int或字符串
How to search for a specific int or string within an object?
我有一个大对象,在不知道它的路径或位置的情况下,我想在对象中找到一个生成的数字。我如何搜索属性,或者只搜索值,甚至搜索布尔?
即具有属性"版本"值为"90"的对象的对象
var objy = {
example: 'unknown0',
example1: 'unknown1',
example2: 'unknown2',
example3: 'unknown3',
example4: 'unknown4',
example5: {
prop1: 1,
prop2: 2,
prop3: 3,
prop4: 4,
prop5: {
etc1: true,
etc2: false,
etc4: {
version: 90
}
}
}
}
http://jsfiddle.net/J5Avu/
如果不知道眼前的"树",这可能吗?
这里有一个函数,它基本上递归地查看对象的属性,寻找propertyName/propertyValue组合,并跟踪"路径"(jsfiddle)。如果未找到,则返回null
。
function findPropertyAndValueInObject( obj, prop, value, path ) {
if( obj[prop] === value ) {
return path;
}
else {
var foundPath = null;
for( var thisProp in obj ) {
var propValue = obj[thisProp];
if( typeof(propValue) === "object" ) {
foundPath = findPropertyAndValueInObject(propValue, prop, value, path + "." + thisProp);
if( foundPath !== null ) {
break;
}
}
}
return foundPath;
}
}
console.log( findPropertyAndValueInObject( objy, "version", 90, "objy" ) );
//prints out "objy.example5.prop5.etc4"
此函数查找给定对象的属性值,在给定字符串路径匹配。在这里,您将发现它与您的数据之间的关系,然后在这里使用wJ库。下面是独立版本。
对于您的使用,object_find('example5.prop5.etc4.version', object);
将返回90
/**
* Find data into an object using string path
* like : "my.needle.name" into "haystack"
* @param path
* @param object object
* @returns {*}
*/
function object_find(path, object) {
var base = object, item;
path = path.split('.');
while (path.length > 0) {
item = path.shift();
if (base.hasOwnProperty(item)) {
base = base[item];
if (path.length === 0) {
return base;
}
}
}
return false;
}
相关文章:
- 为什么不'将字符串转换为int不正确(parseInt)
- 将混合字符串和int参数传递给javascript
- 在javascript中将字符串转换为int时出错
- Javascript-将字符串转换为Int会返回NaN错误
- Google 电子表格脚本 getValues - 强制使用 int 而不是字符串
- JavaScript 将字符串转换为带括号的 int 数组
- 在 JavaScript 中将字符串转换为 int 失败
- string.prototype.search('$') 在每个字符串上返回正 int
- 如何将字符串转换为来自按钮输入的 Int
- jQuery/Javascript/AJAX response:将字符串而不是 int 传递到函数中
- Javascript 字符串到 int 转换
- 为什么对于可被10整除的数字,字符串到int之间的转换不能像预期的那样工作
- 从Javascript Int到Java字符串
- 递增字符串中的字母-将char视为int,而不使用.charCodeAt(0)
- 为什么我可以按int而不是字符串进行筛选
- 用JS解析两个HTML字符串,并将其中一个转换为Int
- 如何在对象中搜索特定的int或字符串
- 将一个大数字字符串转换为int
- 如何获取字符串的第一个单词并将其转换为int?jQuery
- 将字符串转换为Int Javascript