首页 > 解决方案 > 将具有多个值的对象和键推送到 for 循环中的数组

问题描述

我有一个单词数组,我想在文本数组中搜索单词,找到它们并检查单词之后的下一个或多个元素是否是数字,将带有单词的数字或数字推送到新对象中并将对象推送到新数组。像这样:

words = ['blue' , 'red' , 'yellow' , 'grin' , 'black' , 'white'];

text = ['xxx'  , 'yyy' , 'red' , 'zzz' , 'black' , 65 , 54 , 'white' , 'aaa' , 'yellow' , 50 , 'ppp'];


Output I want: 

[{'black' : [65 , 54] , 'yellow' : [50]}];  

但是我当前的代码只是返回单词后的数字并将它们推送到新数组中:

words = ['blue' , 'red' , 'yellow' , 'grin' , 'black' , 'white'];

text = ['xxx'  , 'yyy' , 'red' , 'zzz' , 'black' , 65 , 54 , 'white' , 'aaa' , 'yellow' , 50, 'ppp'];

        const set = new Set(words);
        let result = [];
        for (let i = 0; i < text.length; i++) {
          if (set.has(text[i])) {
            while (typeof text[i + 1] == "number") {
              result.push(text[++i]);
            }
          }
        }

      console.log(result)

//output : [65 , 54 , 50]

那么如何将带有键的数字推送到数组中呢?

标签: javascript

解决方案


您没有正确创建对象并将其推送到主数组。您正在检查数组中的节点text是否存在words,如果发现则将找到的单词之后的数字推送到数组correclty。但是您不应该将其推送到普通数组。相反,您应该将其推送到具有您找到的匹配键的对象,它最初应声明为空数组。之后的数字需要被推送到这个数组。

请找到相同的工作小提琴

const words = ['blue', 'red', 'yellow', 'grin', 'black', 'white'];
// const text = ['black'  , 50 , 'black' , 600 , 10 , 'black' , 40];
const text = ['xxx', 'yyy', 'red', 'zzz', 'black', 65, 54, 'white', 'aaa', 'yellow', 50, 'ppp'];
const set = new Set(words);
const finalResult = [];
for (let i = 0; i < text.length; i++) {
  if (set.has(text[i])) {
    const newObj = {};
    const key = text[i];
    const result = [];
    while (typeof text[i + 1] == "number") {
      result.push(text[++i]);
    }
    if (result.length > 0) {
      newObj[key] = result
      finalResult.push(newObj);
    }
  }
}
console.log(finalResult);

Array.reduce您的要求的实现将是这样的

const words = ['blue', 'red', 'yellow', 'grin', 'black', 'white'];
// const text = ['black'  , 50 , 'black' , 600 , 10 , 'black' , 40];
const text = ['xxx', 'yyy', 'red', 'zzz', 'black', 65, 54, 'white', 'aaa', 'yellow', 50, 'ppp'];
const modifiedText = text.reduce((acc, curr, index) => {
  if (typeof text[index] === "string" && typeof text[index + 1] === "number" && words.includes(curr)) {
    const newArr = [];
    let startIndex = index + 1;
    while (text[startIndex] && typeof text[startIndex] === "number") {
      newArr.push(text[startIndex]);
      startIndex++;
    }
    if(newArr.length) {
      acc.push({[curr] : newArr });
    }
  }
  return acc;
}, []);
console.log(modifiedText);


推荐阅读