DEV Community

loading...

Matching Properties and Values in the Object challenge.

Randy Rivera
Once I truly put my mind on something, I won't ever stop.
・2 min read
  • Welcome back I'm sorry that it took me a while to post something. Anyways let's get back straight to it. In this post let's make a function that looks through an array of objects (first argument) and returns an array of all objects that have matching name and value pairs (second argument). Each name and value pair of the source object has to be present in the object from the collection.
  • For example, if the first argument is [{ first: "Randy", last: "Skywalker" }, { first: "Alan", last: null }, { first: "Diego", last: "Rivera" }], and the second argument is { last: "Rivera" }, then you must return the third object from the array (the first argument), because it contains the name and its value, that was passed on as the second argument.

Alright let's get to it then. Below is already pre written for you.

function names(collection, target) {
  var arr = [];
  // Only change code below this line


  // Only change code above this line
  return arr;
}

names([{ first: "Randy", last: "Skywalker" }, { first: "Alan", last: null }, { first: "Diego", last: "Rivera" }], { last: "Rivera" });
Enter fullscreen mode Exit fullscreen mode
  • Answer:
function names(collection, target) {
  let keys = Object.keys(target);

  return collection.filter(function(obj) {
    for (let i = 0; i < keys.length; i++) {
    if (!obj.hasOwnProperty(keys[i]) || obj[keys[i]] !== target[keys[i]]) {
      return false;
    }
  }
    return true;
  })
}

names([{ first: "Randy", last: "Skywalker" }, { first: "Alan", last: null }, { first: "Diego", last: "Rivera" }], { last: "Rivera" }); // console.log would display the entire object [{ first: 'Diego', last: 'Rivera' }]
Enter fullscreen mode Exit fullscreen mode
  • !obj basically means if the obj does not.
  • There's also a slightly different way of doing the for loop as well.
  • Ex:
function names(collection, target) {
  let keys = Object.keys(target);

  return collection.filter(function(obj) {
    for (let key of keys) {
    if (!obj.hasOwnProperty(key) || obj[keys] !== target[keys]) {
      return false;
    }
  }
    return true;
  })
}
Enter fullscreen mode Exit fullscreen mode

Discussion (0)