首页 > 解决方案 > 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'

所以我想在文本数组中搜索,如果wordkey相等,将 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);

感谢您的帮助

标签: javascriptnode.js

解决方案


您可以存储最新找到的类型。

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; }


推荐阅读