javascript - 将具有多个值的对象和键推送到 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]
那么如何将带有键的数字推送到数组中呢?
解决方案
您没有正确创建对象并将其推送到主数组。您正在检查数组中的节点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);
推荐阅读
- android - 如何在 API 级别 21 以下的设备中检查 NO INTERNET
- php - PHP:SimpleXMLElement 不解析链接标签的 href 属性
- angular - 嵌套的可观察对象,其中最终 API 调用需要使用两个可观察对象的结果
- php - 如何使用 PHP 在下面的代码中设置纵横比
- c - 如果两种类型在 C 中相互“兼容”,这究竟意味着什么?
- r - 显示 YAML 和块而不在 blogdown 中执行它们
- python - 为什么我的代码不执行,我该如何执行?
- ios - 为什么应用在实施 Firebase Crashlytics 时不会崩溃?
- excel - Normal.dot 和 Personal.xlsb
- html - 水平对齐 CSS 箭头和文本