Testing Objects in JS Arrays
I have an array of objects 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 check the value: x
on the : key slug
, but my array of objects is hundreds of objects. Is there a way to check the value without going through all the objects manually?
source to share
Well, somehow you need hinges. But at least JavaScript does 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 this data very often, it would be better to loop once and store each object using 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']
source to share
Question: is a filter or test array needed for the value? If a test, then it is better to use the some () function.
Update: . According to jsPerf http://jsperf.com/json-stringify-vs-array-loop some () is 800x faster, 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'))
source to share