搜索和筛选数组JavaScript

时间:2018-07-18 02:37:35

标签: javascript

请问标题,我不确定如何描述自己在做什么

我有一个文本区域,人们可以在其中写评论,但他们也可以使用我创建的@mention系统提及人们...现在,我的唯一问题是用户在@之后开始键入内容,这并不会缩小用户范围,所以说我有很多这样的对象。

users = [
  {
    name: steve,
    id: 47 
  },
  {
    name: james,
    id: 41
  },
  {
    name: guy,
    id: 44 
  },
  {
    name: troy,
    id: 32 
  }
]

如何根据@符号后面写的字符串来过滤掉数组中的用户,所以如果我在文本区域中写@tr,则用户数组现在应该像这样

users = [
  {
    name: troy,
    id: 32
  }
]

任何帮助将不胜感激!

5 个答案:

答案 0 :(得分:2)

使用filter来检查用户的name是否正在所讨论的子字符串上includes上进行迭代:

const users = [
  {
    name: 'steve',
    id: 47 
  },
  {
    name: 'james',
    id: 41
  },
  {
    name: 'guy',
    id: 44 
  },
  {
    name: 'troy',
    id: 32 
  }
];

const substr = 'tr';
console.log(
  users.filter(({ name }) => name.includes(substr))
);

还要确保您的name值是字符串

答案 1 :(得分:1)

我建议使用与其他答案类似的方法,但是我将使用startsWith而不是include并在比较它们时确保将两个字符串都小写。这将为您提供更准确的结果。

const names = [{ name: 'Bob'}, { name: 'Sally' }, { name: 'Frank' }, { name: 'Lester' }, { name: 'Bo' }, { name: 'Salazar' }, { name: 'Frida' }];
const textArea = document.querySelector('[data-id="textarea"]');
const nameWrap = document.querySelector('[data-id="names"]');

function inputListener() {
  let shouldListen = false;
  let index;
  return (e) => {
    const { value } = e.currentTarget;
    const currentValue = value[value.length - 1];
    if(shouldListen) {
      if(currentValue === ' ' || value.length - 1 < index) {
        shouldListen = false;
        return;
      }
      const str = (value.substr(index).match(/@(.+$)/)[1]).toLowerCase();
      const html = names
        .filter(({ name }) => name.toLowerCase().startsWith(str))
        .map(({ name }) => `<p>${name}</p>`)
        .join('');
        console.log(html)
     nameWrap.innerHTML = html;
    }
    if(currentValue === '@' && !shouldListen) {
      shouldListen = true;
      index = value.length - 1;
    }
  }

}
textArea.addEventListener('input', inputListener())
<textarea data-id="textarea"></textarea>
<div data-id="names"></div>

答案 2 :(得分:0)

尝试一下。

let str = "@tr";

var users = [
  {
    name: "steve",
    id: 47 
  },
  {
    name: "james",
    id: 41
  },
  {
    name: "guy",
    id: 44 
  },
  {
    name: "troy",
    id: 32 
  }
];

const filteredUser = users.filter(user => user.name.includes(str.replace(/@/, "")));
console.log(filteredUser);

答案 3 :(得分:0)

您可能需要filter

const users = [
  {
    name: 'steve',
    id: 47 
  },
  {
    name: 'james',
    id: 41
  },
  {
    name: 'guy',
    id: 44 
  },
  {
    name: 'troy',
    id: 32 
  }, {
    name: 'stephon',
    id: 141
  }
];

const partialUserName = 'st';
const output = users.filter(user => user.name.startsWith(partialUserName)); 
// you can change to contains if that's what you want
console.log(output)

答案 4 :(得分:0)

您可以尝试搜索方法

  const substr = 'tr';
   array.filter(( name ) => {
     return (
      name.toLowerCase()
      .search(substr.toLowerCase()) !== -1
       )

希望获得帮助

相关问题