سؤال

I want to know if there is a way to extract / search the elements which contain similar property from a javascript object.

Just to be more specific, If I have the following object:

Live Demo: http://jsfiddle.net/oscarj24/sMWUL/

var enrolled = {};

enrolled['enrolled/ruby/S1234'] = {
    course: {
        id: 'P01',
        desc: 'Ruby course'
    },
    student: {
        id: 'S1234',
        name: 'John Doe'
    }
};
enrolled['enrolled/php/S1234'] = {
    course: {
        id: 'P02',
        desc: 'PHP course'
    },
    student: {
        id: 'S1234',
        name: 'Foo Bar'
    }
};
enrolled['enrolled/java/S6666'] = {
    course: {
        id: 'P03',
        desc: 'Java course'
    },
    student: {
        id: 'S6666',
        name: 'Bill Gates'
    }
};

Then I'll have some similar properties inside the enrolled object (like the ones sharing the S1234 string at the end).


So, my question is:

How can I extract the elements with string similarities or coincidences in the properties?

I've looked that javascript objects are very limited and the only thing I can do to check if a property exists or not is: obj.hasOwnProperty(prop) (but this is not what I am looking for). Is there a way to use regex to check for this? (just saying, seems not to be possible).

Just to know, I am using ExtJS 4.2 but I can't find something to achieve what I need in the API documentation (correct me if wrong).

هل كانت مفيدة؟

المحلول

You can use a for each loop to see if what you're searching for is in the string.`

for (key in enrolled)
{
     if(key.indexOf('S1234') > -1)
     {      
         console.log(key);
         //Perform your actions here
     }                 
}

Fiddle here: http://jsfiddle.net/brettwlutz/sMWUL/2/

نصائح أخرى

how about this?

for(var prop in enrolled){
console.log(prop);
//check if prop matches string regex.
}
مرخصة بموجب: CC-BY-SA مع الإسناد
لا تنتمي إلى StackOverflow
scroll top