How to match more than one property of an object

Viewed 469

I can match a single property easy enough

var peoples = [
  { "name": "bob", "dinner": "pizza" },
  { "name": "john", "dinner": "sushi" },
  { "name": "larry", "dinner": "hummus" },
  { "name": "john", "dinner": "pie" }
];

$.each(peoples, function(i, val) {
    $.each(val, function(key, name) {
        if (name === "john")
            console.log(key + " : " + name);
       });
});

But since there are 2 johns how do I match a particular one (eg the john that like sushi) and then return the whole matched object (in json)? I tried adding another condition to the if statement but that didn't seem to work.

Thanks

5 Answers

you can use find to check exact match

var peoples = [
  { "name": "bob", "dinner": "pizza" },
  { "name": "john", "dinner": "sushi" },
  { "name": "larry", "dinner": "hummus" },
  { "name": "john", "dinner": "pie" }
];

var filteredResult = peoples.find(val => val.name ==="john" && val.dinner==="sushi");
console.log(filteredResult)

Consider the following.

var peoples = [{
    "name": "bob",
    "dinner": "pizza"
  },
  {
    "name": "john",
    "dinner": "sushi"
  },
  {
    "name": "larry",
    "dinner": "hummus"
  },
  {
    "name": "john",
    "dinner": "pie"
  }
];

$.each(peoples, function(i, val) {
  if (val.name == "john" && val.dinner == "sushi") {
    console.log("Persons[" + i + "]." + Object.keys(val)[0] + ": " + val.name);
  }
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>

This iterates all the items and compares elements of each.

I don't know the context, but there could be two john and both with the dinner property set to pie. I would suggest using id for each entry in the array. If the array you are working with is the one you list, you could project/transform it using map before you perform searches. For example

const people = [
  { name: "bob", dinner: "pizza" },
  { name: "john", dinner: "sushi" },
  { name: "larry", dinner: "hummus" },
  { name: "john", dinner: "pie" },
];

const peopleList = people.map((person, id) => ({ id, ...person }));

console.log(peopleList);

// You could start from here to search by id

_.filter by lodash

You can use filter method by lodash Iterates over elements of collection, returning an array of all elements predicate returns truthy for.The predicate is invoked with three arguments: (value, index|key, collection).It return a new array

https://lodash.com/docs/4.17.15#filter

Example for filter usage on lodash

var users = [{
    'user': 'barney',
    'age': 36,
    'active': true
  },
  {
    'user': 'fred',
    'age': 40,
    'active': false
  },
  {
    'user': 'fred',
    'age': 39,
    'active': true
  }
];

console.log("matches:", _.filter(users, function(o) {
  return !o.active;
}));
// => [{ active: true, age: 36, user: "barney"}]

// The `_.matches` iteratee shorthand.
console.log("_.matches` iteratee", _.filter(users, {
  'user': 'fred',
  'active': true
}));
// => [{ active: true, age: 39, user: "fred"}]

// The `_.matchesProperty` iteratee shorthand.
console.log("matchs poperty", _.filter(users, ['active', false]));
// => objects for ['fred']

// The `_.property` iteratee shorthand.
_.filter(users, 'active');
// => objects for ['barney']
<script src="https://cdnjs.cloudflare.com/ajax/libs/lodash.js/4.17.15/lodash.min.js"></script>

_.where by underscore.js

You can also use where method of underscore.js Looks through each value in the list, returning an array of all the values that matches the key-value pairs listed in properties. _.where(list, properties)

Example of _.where usage _.where(listOfPlays, {author: "Shakespeare", year: 1611});

You can basicaly use filter method in plain vanilla javascript

var peoples = [
  { "name": "bob", "dinner": "pizza" },
  { "name": "john", "dinner": "sushi" },
  { "name": "john", "dinner": "sushi" },
  { "name": "larry", "dinner": "hummus" },
  { "name": "john", "dinner": "pie" }
];

var dinner = peoples.filter(e=>e.name ==="john" && e.dinner==="sushi");

console.log(dinner)

You may also use jquery grep

var peoples = [
  { "name": "bob", "dinner": "pizza" },
  { "name": "john", "dinner": "sushi" },
  { "name": "john", "dinner": "sushi" },
  { "name": "larry", "dinner": "hummus" },
  { "name": "john", "dinner": "pie" }
];

var dinner = $.grep(peoples, function(people) {
    return people.name === "john" && people.dinner === "sushi";
});

console.log(dinner)
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>

Find vs filter

var peoples = [
  { "name": "bob", "dinner": "pizza" },
  { "name": "john", "dinner": "sushi" },
  { "name": "john", "dinner": "sushi" },
  { "name": "larry", "dinner": "hummus" },
  { "name": "john", "dinner": "pie" }
];

var filterDinner = peoples.filter(e=>e.name ==="john" && e.dinner==="sushi");

// return all matching results
console.log('filter dinner -:', filterDinner);

var findDinner = peoples.find(e=>e.name ==="john" && e.dinner==="sushi");

//returns the first matching rslt
console.log('find dinner -:', findDinner);

Find was not recommended because it return the first matching result and suppose we have more matching results they are missed out.

You could set up a function to define your search terms then use Array.filter:

const peoples = [
  { "name": "bob", "dinner": "pizza" },
  { "name": "john", "dinner": "sushi" },
  { "name": "larry", "dinner": "hummus" },
  { "name": "john", "dinner": "pie" }
];

searchTerms = (person) => {
  return person.name === "john" && person.dinner === "sushi";
}

console.log(peoples.filter(searchTerms));

// [{ "name": "john", "dinner": "sushi" }]
Related