根据条件的位置按属性过滤对象数组

时间:2018-03-28 12:58:56

标签: angular lodash

我需要过滤特定属性与用户类型相匹配的对象数组。

鉴于此

peopleList = [ 
  {name: "john bee", age:23},
  {name: "john woo", age:43},
  {name: "jim foo", age:101},
  {name: "bob wow", age:67},
  {name: "last john", age:43},
]

一旦用户键入第一个字符,我想根据完全匹配而不是“喜欢哪里”来过滤数组。

我检查了这个问题: Filtering array of objects with lodash based on property value

但它只返回一个完全匹配或没有。

我可以使用什么lodash函数返回一个对象数组,其中name属性与用户输入的查询字符串匹配,这样如果用户输入'Jo',则返回:

[ 
  {name: "john bee", age:23},
  {name: "john woo", age:43},
  {name: "last john", age:43},
]

如果重要,我正在使用Angular。

3 个答案:

答案 0 :(得分:2)

在es6语法中,它看起来像

const filteredArray = peopleList.filter( people => people.name.includes(someText) );

答案 1 :(得分:2)

这是没有lodash和普通javascript的工作片段:



var peopleList = [ 
  {name: "john bee", age:23},
  {name: "john woo", age:43},
  {name: "jim foo", age:101},
  {name: "bob wow", age:67},
  {name: "last john", age:43},
];

var result = peopleList.filter(person => person.name.includes("jo"));

console.log(result);




答案 2 :(得分:1)

试试这个

const peopleList = [ 
  {name: "john bee", age:23},
  {name: "john woo", age:43},
  {name: "jim foo", age:101},
  {name: "bob wow", age:67},
  {name: "last john", age:43},
]
const search = "jo"

cosnt subList = peopleList.filter((person)=>person.name.indexOf(search) > -1)