简体   繁体   English

JavaScript在JSON对象中查找属性

[英]JavaScript find property in JSON object

I have a JSON object that looks a bit like this: 我有一个看起来像这样的JSON对象:

{
    name: 'test',
    details: {
        description: 'This is the long description',
        shortDescription: 'This is the short description (ironically longer than the description!)'
    }
}

Obviously the real object is a lot more complicated than this example, but I have omitted the details because they will only complicate the question. 显然,实际对象比该示例要复杂得多,但是我省略了细节,因为它们只会使问题复杂化。 So, with this object, I have a function that tries to get the value of the property, it looks like this: 所以,有了这个对象,我有一个试图获取属性值的函数,它看起来像这样:

// 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;
}

The issue is the line: 问题是这条线:

var text = item[filter.field],

If the property was just the name then item['name'] would work with the above object. 如果属性只是名称,item ['name']将与上述对象一起使用。 But if I want to get the description; 但是如果我想得到描述, item['details.descrption'] doesn't work. item ['details.descrption']不起作用。 So I need a function that will allow me to specify a property name and it will find the property and return its value. 所以我需要一个允许我指定属性名称的函数,它将找到属性并返回其值。 But before I try to write one, I was hoping there might be a simple solution that someone has come across. 但在我尝试编写之前,我希望可能有一个简单的解决方案,有人遇到过。

You can split the reference to the object and use a function for getting the right nested object/value. 您可以拆分对对象的引用,并使用一个函数来获取正确的嵌套对象/值。

 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')); 

you can write your custom function for this 你可以为此编写自定义函数

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;
}

check this plnkr example https://plnkr.co/edit/8Ayd9wnh1rJh1ycx5R1f?p=preview 检查这个plnkr示例https://plnkr.co/edit/8Ayd9wnh1rJh1ycx5R1f?p=preview

I solved this by creating this function: 我通过创建此函数解决了这个问题:

// 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);
            }
        }
    }
};

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM