繁体   English   中英

JavaScript:使用 object 过滤对象数组

[英]JavaScript: filter array of objects using an object

我试图从freecodecamp做以下挑战: https://www.freecodecamp.org/learn/javascript-algorithms-and-data-structures/intermediate-algorithm-scripting/wherefore-art-thou我有几个问题关于它。

  1. 为什么我的尝试在我的本地控制台上工作,而不是在 freecodecamp 上? 意思是,在所有测试中,4 个中有 3 个在我的控制台中是正确的,但没有一个在 FCC 上。
  2. 为什么这个测试whatIsInAName([{ "apple": 1, "bat": 2 }, { "bat": 2 }, { "apple": 1, "bat": 2, "cookie": 2 }], { "apple": 1, "bat": 2 })如果所有其他人都通过了?

我的预期结果尝试:

 function whatIsInAName(collection, source) { const arr = []; // Only change code below this line let finalObj = collection.map(item => Object.entries(item)).filter(el => String(el).includes(String(Object.values(source)))).map(el => Object.fromEntries(el)) arr.push(finalObj); console.log(arr); // Only change code above this line return arr; } whatIsInAName([{ first: "Romeo", last: "Montague" }, { first: "Mercutio", last: null }, { first: "Tybalt", last: "Capulet" }], { last: "Capulet" }) // should return [{ first: "Tybalt", last: "Capulet" }] whatIsInAName([{ "apple": 1 }, { "apple": 1 }, { "apple": 1, "bat": 2 }], { "apple": 1 }) // should return [{ "apple": 1 }, { "apple": 1 }, { "apple": 1, "bat": 2 }] whatIsInAName([{ "apple": 1, "bat": 2 }, { "apple": 1 }, { "apple": 1, "bat": 2, "cookie": 2 }], { "apple": 1, "cookie": 2 }) // should return [{ "apple": 1, "bat": 2, "cookie": 2 }] whatIsInAName([{ "apple": 1, "bat": 2 }, { "apple": 1 }, { "apple": 1, "bat": 2, "cookie": 2 }, { "bat":2 }], { "apple": 1, "bat": 2 }) // should return [{ "apple": 1, "bat": 2 }, { "apple": 1, "bat": 2, "cookie":2 }] whatIsInAName([{"a": 1, "b": 2, "c": 3}], {"a": 1, "b": 9999, "c": 3}) // should return []

  • 使用Object#entries ,从source获取键值对列表
  • 使用Array#filter迭代collection 在每次迭代中,使用Array#every检查上述sourceEntries中的所有条目是否与当前 object 匹配

 function whatIsInAName(collection, source) { const sourceEntries = Object.entries(source); return collection.filter(e => sourceEntries.every(([key, value]) => e[key] === value) ); } console.log( whatIsInAName([{ first: "Romeo", last: "Montague" }, { first: "Mercutio", last: null }, { first: "Tybalt", last: "Capulet" }], { last: "Capulet" }) ); console.log( whatIsInAName([{ "apple": 1 }, { "apple": 1 }, { "apple": 1, "bat": 2 }], { "apple": 1 }) ); console.log( whatIsInAName([{ "apple": 1, "bat": 2 }, { "bat": 2 }, { "apple": 1, "bat": 2, "cookie": 2 }], { "apple": 1, "bat": 2 }) ); console.log( whatIsInAName([{ "a": 1, "b": 2, "c": 3 }], { "a": 1, "b": 9999, "c": 3 }) );

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM