Where Art Thou
1. Requirements
- Write a function that iterates through an array of objects (the first parameter) and returns an array of all objects that contain matching property-value pairs (the second argument).
- If the returned array contains property-value pairs for the source object, then each property-value pair of this object must exist in the collection object.
2. Ideas
- Remove the property of source with Object.keys (source)
- Use Object.keys () to iterate through the properties of the collection all child elements in the for loop, set the mark tag variable, and initially true in a layer loop.
- Mark becomes false when encountering a collection child element without a Sourse attribute in the For loop or when two corresponding property values are not equal
- A layer of loops finally, if Mark is true, push the corresponding collection child element to the result array
3. Code
function where(collection, source) {var arr = [];var arrj = Object.keys(source);for(var i = 0; i<collection.length; i++){ var arri = Object.keys(collection[i]); var mark = true; for (var j = 0; j < arrj.length; j++){ if (arri.indexOf(arrj[j]) === -1 || collection[i][arrj[j]] !== source[arrj[j]]) { mark =false; } } if (mark){ arr.push(collection[i]); }}// What‘s in a name?return arr;}where([{ first: "Romeo", last: "Montague" }, { first: "Mercutio", last: null }, { first: "Tybalt", last: "Capulet" }], { last: "Capulet" });
4. RELATED LINKS
- Https://developer.mozilla.org/zh-CN/docs/Web/JavaScript/Reference/Global_Objects/Object/keys
Where Art Thou-freecodecamp algorithm topics