In Javascript, given value, find value and filter on the specific value from Object literal

130 views Asked by At

I should note I am not the best with Javascript/ajax/jquery. Anyway, I am in need of some assistance when it comes to checking an object to see if it contains a certain value based on an object literal. I am using the JavaScript InfoVis Toolkit for a project I am working on. The library visualization I am using isn't using a true json object, but more of a javascript object literal. I'm having a hard time seeing if an item exists in my object.

I tried the best answer provided after making changes to fit my code, however, it does not seem to work properly.

I've also tried a for..in loop which I know is frowned upon (plus I didn't get this to work as expected either)

Here is the object and its structure:

 myObj = {
    id: "190_0",
    name: "Pearl Jam",
    children: [{
        id: "306208_1",
        name: "Pearl Jam & Cypress Hill",
        children: [{
            id: "84_2",
            name: "Cypress Hill",
            children: []
        },
        {
            id: "306208_3",
            name: "Alex"
        }]
    }]
};

[EDIT] I am trying to get to "Alex" in this example, but everything I've attempted fails. I'd need it to look through the entire structure, so I can't have hard-coded selections (myObj.children[0].name....)

The end goal for my project is to be able to search for users whom have a specific skill set. So for example:

I want to search for the skillset C++, then show all the children of C++ (which would be people's names). [/EDIT]

Thank you in advance for any help.

1

There are 1 answers

1
Benjamin Gruenbaum On BEST ANSWER

After the clarification here is a recursive way to check that:

Here is a small implementation

function contains(obj,what){
    if(obj === what){ 
        return true;
    }
    if(typeof obj!== "object" || obj === null){
        return false;
    }
    for(var i in obj){
        if(contains(obj[i],what)){
            return true;
        }
    }
   return false;
}

This works in all browsers new and old and has no dependencies. Once again annotated:

function contains(obj,what){
    if(obj === what){ // if the object is what we're looking for - return it
        return true;
    }
    // if it's not what we're looking for and it's not an object return it
    if(typeof obj!== "object" || obj === null){
        return false;
    }
    for(var i in obj){ // check if it's any of its properties
        if(contains(obj[i],what)){
            return true; // found it in a child
        }
    }
   return false; // did not find it anywhere.
}

Also, obligatory one liner:

function contains(obj,what){
    return (obj === what)||((typeof obj === "object" && obj !== null) &&  Object.keys(obj).some(function(el){return contains(obj[el],what);}));
}