0

I have an object in javaScript:

var stuffObject = {
     stuffArray1 : [object1, object2, object3],
     stuffArray2 : [object4, object5, object6]
}

object1 to 6 look like this:

object1 = {
   dataStuff : {
       stuffId: "foobar"
   }
}

My question: given the key "foobar", how do I retrieve object1 from the stuffObject using jQuery? The key "stuffId" always has a unique value.

2 Answers 2

1

You won't get around iterating over the set to find the object you are looking for. jQuery can't really help with that. Its purpose is DOM manipulation. If you want functionality to deal with objects, sets, lists, etc., check out lodash.

I wrote a function to deal with the problem. I hope it's understandable.

var stuffObject = {
    stuffArray1 : [{dataStuff: {stuffId: 'foobar'}}, {dataStuff: {stuffId: 'foo'}}, {}],
    stuffArray2 : [{}, {dataStuff: {stuffId: 'bar'}}, {}]
}

function getObjByStuffId(stuffObject, stuffId) {
    var key, arr, i, obj;
    // Iterate over all the arrays in the object
    for(key in stuffObject) {
        if(stuffObject.hasOwnProperty(key)) {
            arr = stuffObject[key];
            // Iterate over all the values in the array
            for(i = 0; i < arr.length; i++) {
                obj = arr[i];
                // And if it has the value we are looking for
                if(typeof obj.dataStuff === 'object'
                   && obj.dataStuff.stuffId === stuffId) {
                    // Stop searching and return the object.
                    return obj;
                }
            }
        }
    }
}

console.log('foobar?', getObjByStuffId(stuffObject, 'foobar') );
console.log('foo?', getObjByStuffId(stuffObject, 'foo') );
console.log('bar?', getObjByStuffId(stuffObject, 'bar') );
Sign up to request clarification or add additional context in comments.

Comments

0

Thanks for the help guys, using the input of other people I have solved it myself:

getStuffById: function(id){
    for (stuffArray in stuffObject) {
            for (stuff in stuffObject[stuffArray]) {
                if (stuffObject[stuffArray][stuff].dataStuff.stuffId == id) {
                    return stuffObject[stuffArray][stuff];
                }
            }
        }
    return null;
}

This also works better than the (now deleted) answer that uses .grep(), as this function terminates as soon as it finds the correct object.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.