0

There is an array of objects in javascript. i need to look for an attribute value for that object within that array. All the objects with the matching attributes i need to put them in another array. I'm beginner in jquery, any help would be really appreciated. Thanks.

 var numPerRow = 6;
        for (var i=0; i<subjects.length; i+=numPerRow) {
            // TODO: Implement a row view
var printTitle = subjects[i].getTitle();
if (printTitle.indexOf(searchValue) > -1)
{
            var row = $('<div class="browse-printables-row"></div>');
            for (var j=0; j<numPerRow; j++) {
                var idx = i+j;
                if (idx >= subjects.length) {
                    break;
                }
                // TODO: Implement a printables tile view
                row.append($(
                    '<div class="printable-tile">' +
                        '<img src=' + printTitle[idx].getIconURL() + ' class="subject-tile-icon"></img>' +
                        '<div class="subject-tile-title">' + printTitle[idx].getTitle() + '</div>' +
                    '</div>'
                ));
            }
}
            grid.append(row);
4
  • Please post some code and what have you tried so far? Commented Jun 12, 2013 at 14:40
  • 2
    At the very least please post your input (the array), and your expected output. Commented Jun 12, 2013 at 14:41
  • 1
    @DavidThomas, no! You guys do my work, and guess what I need! Commented Jun 12, 2013 at 14:42
  • I just added code. sorry for not putting it earlier Commented Jun 12, 2013 at 14:48

2 Answers 2

1

Read about array's filter method

Example will filter array and return only objects where attribute b equal to 2:

var filtered = [{a: 1, b: 2}, {a: 5, b:2}, {a:2, b:1}].filter(function(el, index, array) {
    if(typeof el.b === 'undefined') return false;
    return (el.b === 2);
});
Sign up to request clarification or add additional context in comments.

2 Comments

Why not simplify: return typeof el.b === 'undefined' ? false : el.b;?
I've wrote example to get some specific objects (where attribute b is equal to two) you need to correct your version to 'el.b === 2'. I totally agree that it can be written shorter but I don't agree that short hand 'if' statement is more simpl to read. BTW if you want to check if there is attribute in array of objects your example will not work properly as el.b can be equal to zero and filter's callback function will return 0 which is equal to false.
1

Skeleton answer for skeleton question

//declare array
if(jQuery.inArray(yourObj, arrayOfObjs) === -1)
{
not found
}
else
{
found //push in to array
}

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.