javascript - 打印数组存在的名称
问题描述
我有这段代码:
var data = {
sand: [['sun', 'moon', 'cool'], ['man', 'store', 'rose', 'big', 'you', 'sharp', 'low', 'high'], ['hot', 'cool', 'lip'], ['store', 'man', 'lip']],
king: [['store', 'man', 'lip'], ['store', 'man', 'lip'], ['store', 'man', 'lip']],
house: [['lip', 'store', 'hot', 'bed', 'you', 'low', 'run', 'high'], ['cool', 'sun', 'hot', 'big', 'sharp', 'low', 'run', 'high'], ['high', 'cool', 'moon', 'lip', 'man'], ['man', 'store', 'rose', 'big', 'you', 'sharp', 'low', 'high']],
bow: [['lip', 'store', 'hot', 'bed', 'you', 'low', 'run', 'high'], ['bed', 'moon', 'lip'], ['low', 'cool', 'lip', 'man']],
queen: [['cool', 'awe'], ['low', 'dad'], ['usa', 'cool', 'ita'], ['bed', 'glass', 'store', 'sal']],
}
我想打印所有['store', 'man', 'lip']
存在的名称。所以,应该打印的是:沙,王。我怎样才能做到这一点?
解决方案
您可以通过检查值与同一索引处的集合的值来为每个数组获取一个集合,以便与对象的键进行比较和过滤。
function getKeys(object, pattern) {
return Object
.keys(data)
.filter(key => data[key].some(a =>
a.length === pattern.length &&
pattern.every((p, i) => a[i] === p)
));
}
var data = {
sand: [['sun', 'moon', 'cool'], ['man', 'store', 'rose', 'big', 'you', 'sharp', 'low', 'high'], ['hot', 'cool', 'lip'], ['store', 'man', 'lip']],
king: [['store', 'man', 'lip'], ['store', 'man', 'lip'], ['store', 'man', 'lip']],
house: [['lip', 'store', 'hot', 'bed', 'you', 'low', 'run', 'high'], ['cool', 'sun', 'hot', 'big', 'sharp', 'low', 'run', 'high'], ['high', 'cool', 'moon', 'lip', 'man'], ['man', 'store', 'rose', 'big', 'you', 'sharp', 'low', 'high']],
bow: [['lip', 'store', 'hot', 'bed', 'you', 'low', 'run', 'high'], ['bed', 'moon', 'lip'], ['low', 'cool', 'lip', 'man']],
queen: [['cool', 'awe'], ['low', 'dad'], ['usa', 'cool', 'ita'], ['bed', 'glass', 'store', 'sal']],
},
pattern = ['store', 'man', 'lip'];
console.log(getKeys(data, pattern));
推荐阅读
- apache-kafka - 扩展 Kafka:如何动态添加新的事件处理能力?
- postgresql - DB2 命令更改为 Postgres 命令
- sockets - 如何在 Rust 中将 SocketAddr 转换为字符串?
- c# - 在不使用 IDENTITY 的情况下在我的控制器中增加 id(编号)
- python - 进程在获取字体时以退出代码 1 完成
- postgresql-10 - 无法从 pg_dump 恢复完整的数据库
- flutter - 带有不需要的填充/额外宽度的颤动材质按钮
- multithreading - Jmeter将线程数作为动态值传递
- java - 为什么使用 set = map.entryset(); 时不必初始化集合?
- parse-platform - 使用 graphql 对解析服务器挂载的 POST 请求返回 400 Bad Request