我有一个看起来像这样的JSON对象:
{
name: 'test',
details: {
description: 'This is the long description',
shortDescription: 'This is the short description (ironically longer than the description!)'
}
}
显然,真实对象比这个例子复杂得多,但我省略了细节,因为它们只会使问题复杂化。 所以,有了这个对象,我有一个试图获取属性值的函数,它看起来像这样:
// Private function for matching fields
var _matchField = function (item, filter) {
// Our variables
var text = item[filter.field],
values = filter.expression.split(',');
// If we have any text
if (text) {
// Loop through our values
angular.forEach(values, function (value) {
console.log(text);
console.log(value);
// See if we have a match
if (text.toLowerCase().indexOf(value.toLowerCase()) > -1) {
// We have found a match
return true;
}
});
}
// We have found no matches
return false;
}
问题在于:
var text = item[filter.field],
如果该属性只是名称,那么 item ['name'] 将适用于上述对象。但如果我想得到描述; item ['details.descrption'] 不起作用。 所以我需要一个允许我指定属性名称的函数,它将找到属性并返回其值。 但在我尝试编写之前,我希望可能有一个人遇到的简单解决方案。
答案 0 :(得分:0)
您可以拆分对象的引用,并使用函数获取正确的嵌套对象/值。
function getValue(o, p) {
if (typeof p === 'string') {
p = p.split('.')
}
return p.length ? getValue(o[p.shift()], p) : o;
}
var item = { name: 'test', details: { description: 'This is the long description', shortDescription: 'This is the short description (ironically longer than the description!)' } };
document.write(getValue(item, 'details.description'));
答案 1 :(得分:0)
您可以为此
编写自定义函数function getProperty(json, field) {
if (json == null || field == null) {
return null;
}
var value = json;
var fields = field.split(".");
for (var i = 0; i < fields.length; i++) {
value = value[fields[i]];
if (value == null) {
return null;
}
}
return value;
}
检查此plnkr示例https://plnkr.co/edit/8Ayd9wnh1rJh1ycx5R1f?p=preview
答案 2 :(得分:0)
我通过创建这个函数来解决这个问题:
// 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);
}
}
}
};