我有一个函数,通过名称在嵌套对象中查找属性并返回其值。 我从这个网站上的另一个问题得到的功能,到目前为止它一直很好用。 我看起来像这样:
var _getPropertyValue = function (obj, field) {
// Create a result
var result = null;
// If our object is an array
if (obj instanceof Array) {
// For each array item
for (var i = 0; i < obj.length; i++) {
// Invoke our function for the current object
result = _getPropertyValue(obj[i], field);
// If we have a result
if (result) {
// Exit the loop
break;
}
}
// If we are an object
} else {
// For each property in our object
for (var prop in obj) {
// If our property matches our value
if (prop == field) {
// Return our value
return obj[prop];
}
// If our property is an object or an array
if (obj[prop] instanceof Object || obj[prop] instanceof Array) {
// Invoke our function for the current object
result = _getPropertyValue(obj[prop], field);
// If we have a result
if (result) {
// Exit the loop
break;
}
}
}
}
// Return our result
return result;
};
现在,我想也许如果我有这样的对象:
{
name: 'test',
mode: 'default',
settings: {
mode: 'auto'
}
}
使用我的功能,我相信它会找到第一个模式,然后退出该功能。 我更喜欢做的是指定字段参数,如下所示:
settings.mode
并直接转到我对象中的那个地方并返回值。 有谁知道是否可以这样做?
尽管这个被关闭了。 我自己这样回答:
// Private function to get the value of the property
var _getPropertyValue = function (object, notation) {
// Get all the properties
var properties = notation.split('.');
// If we only have one property
if (properties.length === 1) {
// Return our value
return object[properties];
}
// Loop through our properties
for (var property in object) {
// Make sure we are a property
if (object.hasOwnProperty(property)) {
// If we our property name is the same as our first property
if (property === properties[0]) {
// Remove the first item from our properties
properties.splice(0, 1);
// Create our new dot notation
var dotNotation = properties.join('.');
// Find the value of the new dot notation
return _getPropertyValue(object[property], dotNotation);
}
}
}
};
我进一步改善了这个:
// Private function to get the value of the property
var _getPropertyValue = function (obj, notation) {
// Get our properties
var properties = notation.split('.');
// Use reduce to get the value of the property
return properties.reduce(function (a, b) {
// Return our value
return a[b];
}, obj);
};
答案 0 :(得分:0)
var obj = {
name: 'test',
mode: 'default',
settings: {
mode: 'auto'
}
};
var mode = obj.settings.mode;