Writing Custom functions to grab data from JSON

Posted on

Problem

I’m working on a project where i am using VueJS as front-end framework.

I’ve so much data in JSON format to work with for that i’ve written a helper function to retrieve data from JSON. much like we query SQL for table rows.

here is what i wrote

function getWhere(field, value) { 
   var result = [];

    $vm.services.forEach(function(object, key){
       if(object[field] == value) { 
            result.push(object) 
        }
    })   

   return result.length == 1 ? result[0] : result;
 }

2 Questions

  • Is it okay to grab data from JS objects like this i mean iterating the whole object to get a single field?

  • Is there a built-in solution in JS or VueJS for this kind of tasks, if Yes should i use those solutions or the function i posted here is okay to use.

Solution

result[0] : result

This is a bad idea. This will keep users of your functions guessing and unnecessarily put in guard logic to check if it’s a thing, or an array of things before proceeding. If you expect many results, then always return an array. If you expect just one result, return just one (regardless of how many match), and null if none.

iterating the whole object to get a single field

Array searches are O(n) at worst. Tough luck if you’re item is on the tip of the list. While we can’t do anything in the complexity side of things, your code could be simplified. Seeing $vm.services appears to be an array, you can just use array.filter.

// Will always return an array, regardless of match count
function getWhere(field, value) { 
  return $vm.services.filter(function(object){
    return object[field] === value;
  });
});

Alternatively, if you just really want one item among all matches, then array.find is your guy. It takes the same form as filter, but stops going through the array when it hits a match and just returns that one item, without wrapping it in an array.

// Will always return 1 item from the array, and undefined if none
function getWhere(field, value) { 
  return $vm.services.find(function(object){
    return object[field] === value;
  });
});

Is there a built-in solution in JS or VueJS for this kind of tasks, if Yes should i use those solutions or the function i posted here is okay to use.

Yes, filter and find are just a few of many. See array methods.

Leave a Reply

Your email address will not be published. Required fields are marked *