Your Web News in One Place

Help Webnuz

Referal links:

Sign up for GreenGeeks web hosting
July 22, 2021 11:27 pm GMT

Matching Properties and Values in the Object.

  • 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" });
  • 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' }]
  • !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;  })}

Original Link: https://dev.to/rthefounding/matching-properties-and-values-in-the-object-4g4e

Share this article:    Share on Facebook
View Full Article

Dev To

An online community for sharing and discovering great ideas, having debates, and making friends

More About this Source Visit Dev To