jquery JavaScript数组搜索和过滤器[已关闭]

yb3bgrhw  于 2024-01-07  发布在  jQuery
关注(0)|答案(2)|浏览(165)

已关闭。此问题需要details or clarity。目前不接受回答。
**要改进此问题吗?**通过editing this post添加详细信息并阐明问题。

上个月关门了。
Improve this question
我想根据关键字创建一个新数组。
如果我搜索关键字是

  • “居中”结果应为[“居中”]
  • “align”结果应为[“左对齐”,“右对齐”,“右对齐”]
  • “right”结果应该是[“右-右”]
  • “arrow”结果应为[“左-左”,“右-右”]
  1. const myarray = [
  2. {
  3. "align-center": [
  4. "align",
  5. "center"
  6. ]
  7. },
  8. {
  9. "align-justify": [
  10. "align",
  11. "justified"
  12. ]
  13. },
  14. {
  15. "align-left": [
  16. "align",
  17. "left",
  18. "arrow"
  19. ]
  20. },
  21. {
  22. "align-right": [
  23. "align",
  24. "right",
  25. "arrow"
  26. ]
  27. }
  28. ]
  29. let results = myarray.filter(function (name) { return *****
  30. });

字符串

h7wcgrx3

h7wcgrx31#

首先使用map()获取数组中每个对象的键。然后使用filter()返回与搜索字符串匹配的对象。

  1. let searchKey = 'left';
  2. function search(array, searchKey) {
  3. return array.map(obj => Object.keys(obj)[0]).filter(key => key.includes(searchKey));
  4. }
  5. console.log(search(myarray, 'align-center'));
  6. console.log(search(myarray, 'align'));
  7. console.log(search(myarray, 'right'));

个字符

qc6wkl3g

qc6wkl3g2#

你可以创建一个表示相反关系的对象:

  1. const myarray = [{"align-center": ["align","center"]},{"align-justify": ["align","justified"]},{"align-left": ["align","left","arrow"]},{"align-right": ["align","right","arrow"]}]
  2. const transposed = myarray
  3. .flatMap(Object.entries)
  4. .flatMap(([key, values]) => values.map(value => [value, key]))
  5. .reduce((acc, [value, key]) => ((acc[value] ??= []).push(key), acc), {});
  6. console.log(transposed);

字符串

相关问题