javascript - Node.js :返回数组中两个特定元素之间的元素
问题描述
我有一个文本数组和一个对象,对象键有这些数组值:
text = ['CALX' , 'ENTRY' , 43 , 44 , 'TAR' , 50 , 51 , 52 , 'OK', 'XX' , 'SL' , 12 , YYY]
obj = {
entry : ['ENTRY' , 'ENTER' , 'ENT'],
target :['TARGET' , 'TP' , 'TAR' , 'TARGETS'],
sl : ['STOP' , 'SLOSS' , 'SL' , 'SELL'],
}
简化:
word = 文本数组元素(如'CALX'
)
键= 对象值数组元素(如'ENTRY'
或'TP'
所以我想在文本数组中搜索,如果word与key相等,将 word 之后的元素推送到结果对象中的键名数组,直到文本数组中的后一个元素是另一个键或当前键
例如,从文本数组和 obj 中,我想要这个输出:
result = {
entry: [43 , 44],
target: [50 , 51 , 52 , 'OK' , 'XX'],
sl: [12 , 'YYY']
}
这是我的代码,我不知道如何在当前单词之后返回单词:
text = ['CALX' , 'ENTRY' , 43 , 44 , 'TAR' , 50 , 51 , 52 , 'OK', 'XX' , 'SL' , 12 , YYY]
obj = {
entry : ['ENTRY' , 'ENTER' , 'ENT'],
target :['TARGET' , 'TP' , 'TAR' , 'TARGETS'],
sl : ['STOP' , 'SLOSS' , 'SL' , 'SELL'],
}
result = {
entry: [43 , 44],
target: [50 , 51 , 52 , 'OK' , 'XX'],
sl: [12 , 'YYY']
}
for (var i = 0; i < text.length; i++) {
var word = text[i];
for (var j = 0; j < Object.keys(obj).length; j++) {
var objKeys = Object.keys(obj);
var a = obj[objKeys[j]];
for (var k = 0; k < a.length; k++) {
if (word == a[k]) {
}
}
}
}
console.log(result);
感谢您的帮助
解决方案
您可以存储最新找到的类型。
const
text = ['CALX' , 'ENTRY' , 43 , 44 , 'TAR' , 50 , 51 , 52 , 'OK', 'XX' , 'SL' , 12 , 'YYY'],
types = { entry : ['ENTRY' , 'ENTER' , 'ENT'], target :['TARGET' , 'TP' , 'TAR' , 'TARGETS'], sl : ['STOP' , 'SLOSS' , 'SL' , 'SELL'] },
result = {};
let type;
for (const item of text) {
let temp = Object.keys(types).find(k => types[k].includes(item));
if (temp) {
type = temp;
result[type] = result[type] || []; // newer: result[type] ??= [];
continue;
}
if (type) result[type].push(item);
}
console.log(result);
.as-console-wrapper { max-height: 100% !important; top: 0; }
推荐阅读
- python - ^= 在 python 中做了什么
- javascript - React JS - 为什么我需要将 e.target 分配给 const 才能使用 e.target.value?
- c - 为什么这个变量在传递给函数时会改变
- depth-first-search - 这是 BFS 和 DFS 的正确顺序吗?
- caching - 如果页面先前已缓存,是否会看到新的缓存控制标头?
- php - 如何从会话中注销?
- directus - 检索由语言环境指定的文章列表(Directus 翻译)
- build - 如何在 _config.yml 中使用环境变量?
- elasticsearch - 具有多个类别的弹性搜索查询
- bash - 防止 tmux 的 pane_title 被更新