-
慕哥9229398
您可以使用对象的条目构建一个过滤器,并循环访问所有条目并检查值。然后映射名称。let array = [{ name: "john", description: { height: 5.5, weight: 54 } }, { name: "mary", description: { height: 5.8, weight: 65 } }, { name: "smith", description: { height: 6.1, weight: 85 } }], object = { height: 5.8, weight: 65 }, filters = Object.entries(object), result = array .filter(({ description }) => filters.every(([key, value]) => description[key] === value)) .map(({ name }) => name);console.log(result);
-
胡子哥哥
您必须将所需的键相互比较,而不是比较对象,因为对象相等性基于它们的内存地址是否相同。let arr = [ { name: "john", description: { height: 5.5, weight: 54 } }, { name: "mary", description: { height: 5.8, weight: 65 } }, { name: "smith", description: { height: 6.1, weight: 85 } }];let obj = { height: 5.8, weight: 65};console.log( arr.filter(item => item.description.height === obj.height && item.description.weight === obj.weight));
-
慕盖茨4494581
一种方法是使用 .Object.keysvar arr = [ { name: "john", description: { height: 5.5, weight: 54, }, }, { name: "mary", description: { height: 5.8, weight: 65, }, }, { name: "smith", description: { height: 6.1, weight: 85, }}];var obj = { height: 5.8, weight: 65 };var result = arr.filter(({description})=>Object.keys(description).every(k=>description[k]==obj[k])).map(({name})=>name);console.log(result);
-
海绵宝宝撒
您可以缩小要过滤的属性范围,如下所示 let arr = [{ name: "john", description: { height: 5.5, weight: 54 } }, { name: "mary", description: { height: 5.8, weight: 65 } }, { name: "smith", description: { height: 6.1, weight: 85 } } ]; let obj = { height: 5.8, weight: 65 }; const filtered = arr.filter(({ description }) => description.height === obj.height && description.weight === obj.weight); console.log(filtered)
-
阿波罗的战车
筛选器筛选条件失败的根本原因是由于尝试的对象之间的比较。对象的比较可以通过使用帮助程序函数来完成。以下是工作原理:// array-filter-demo.jslet arr = [ { name: "john", description: { height: 5.5, weight: 54 } }, { name: "mary", description: { height: 5.8, weight: 65 } }, { name: "smith",description: { height: 6.1, weight: 85 } } ]let obj = { height: 5.8, weight: 65 }// Helper function to compare objectsfunction matching(a, b) { return ( a.height === b.height && a.weight === b.weight)}// Call the helper function inside filterconst result = arr.filter(item => (matching(item.description, obj)))console.log(result)输出:$ node array-filter-demo.js [ { name: 'mary', description: { height: 5.8, weight: 65 } } ]