Peachey_A
Peachey_A

Reputation: 129

Testing on Objects in JS Arrays

I have an array of objects being returned after an API request. It takes the form:

[{
    id: 12,
    slug: '050e8e8db93ae08ed46cd57017ef9617',
    name: 'Test Badge'
}, {
    id: 13,
    slug: '78ed09b1f2aae29ab30915ac9f167bfa',
    name: 'Test Badge'
}]

I need to test for a value: x on the key: slug, but my array of objects is hundreds of objects long. Is there a way to test for a value without looping through all the objects manually?

Upvotes: 3

Views: 84

Answers (3)

agershun
agershun

Reputation: 4107

Another "non-iterating" option (it is possible here because your key is very specific), but this is slowest because JSON.stringify is slow operation:

function test(x) {
    return JSON.stringify(data).indeхOf(x) > -1;
}

Upvotes: 0

agershun
agershun

Reputation: 4107

Question: do you need filter or test array for value? If test, then it is better to use some() function.

Update: According jsPerf http://jsperf.com/json-stringify-vs-array-loop some() faster in 800 times then filter() and 5000 then JSON.stringify.

    var data = [{
        id: 12,
        slug: '050e8e8db93ae08ed46cd57017ef9617',
        name: 'Test Badge'
    }, {
        id: 13,
        slug: '78ed09b1f2aae29ab30915ac9f167bfa',
        name: 'Test Badge'
    }];

    function test(x) {
        return data.some(function(d){return x==d.slug});
    };

    console.log(test('78ed09b1f2aae29ab30915ac9f167bfa'))

Upvotes: 0

Fuzzyma
Fuzzyma

Reputation: 8474

Well - somehow you have to loop. But at least JavaScript is doin the job for you:

var arr = [
    {
        id: 12,
        slug: '050e8e8db93ae08ed46cd57017ef9617',
        name: 'Test Badge'
    },
    {
        id: 13,
        slug: '78ed09b1f2aae29ab30915ac9f167bfa',
        name: 'Test Badge'
    }
];

var arrWithValue = arr.filter(function(el){ return el.slug === value; });

arrWithValue contains only the elements of the array with the correct value.

When you have to access these data very often it would be better to loop one time and save every object using the slug as key.

var sortedObj = {};
for(var i = 0, len = arr.length; i < len; ++i){
    sortedObj[arr[i].slug] = arr[i];
}

// access the object with sortedObj['someSlug']

Upvotes: 3

Related Questions