JordanBarber JordanBarber - 4 months ago 11
JSON Question

Return Object in Array based on matched data

I have a json array of about 30 objects. Here's a sample object from the array:

{
"id": 0,
"name": "Valle",
"activities": "night-life",
"food": "fancy-food",
"sport" : "baseball",
"geoProfile": "artsy",
"priority": 2
}


I am building out another object on a page based on user input. The user will choose between radio buttons and after they have made their choices, I will have an object such as:

{geoProfile: "artsy", activities: "nature", food: "fancy-food", sport: "cricket"}


I am using jQuery's
$.each()
method to go through each object as follows:

$.each(self.data(), function (i, s) {
if (s.geoProfile == self.prefLocation() &&
s.activities == self.prefActivity() &&
s.food == self.prefFood() &&
s.sport == self.prefSport()) {
optionMatched = s;
return false;
}
});


This will return an object that has all four matches, but how can I return the json object that has the most matches to the user-built object? If two match, I want to then look at the "priority" property and return the one with the lowest priority.

Answer

You could use Array#map and build a new array with the sum of the matched properties.

Later you can sort with map and use the result for sorting and get the first element.

var data = [/* your data here */],
    search = { geoProfile: "artsy", activities: "nature", food: "fancy-food", sport: "cricket" },
    result = data.map(function (a) {
        return {
            count: Object.keys(search).reduce(function (r, k) { return r + +(a[k] === search[k]); }, 0),
            priority: a.priority,
            index: i
        }
    });

result.sort(function (a, b) {
    a.count - b.count || b.priority - a.priority;
});