如何找到等于或大于值的文档数组中的所有值

时间:2019-05-22 18:31:59

标签: javascript node.js

我有一个数组,其中包含这样的文档

[{name: "Tom", age: 20}, {name: "Frank", age: 25}, {name: "Susie", age: 29}, {name: "Tina", age: 32}]

我如何找到所有小于或等于30岁的人?

3 个答案:

答案 0 :(得分:2)

您可以使用filter()

const arr = [{name: "Tom", age: 20}, {name: "Frank", age: 25}, {name: "Susie", age: 29}, {name: "Tina", age: 32}];

const res = arr.filter(x => x.age <=30)
console.log(res)

如果您只想使用人员姓名,请在map()之后使用filter()

const arr = [{name: "Tom", age: 20}, {name: "Frank", age: 25}, {name: "Susie", age: 29}, {name: "Tina", age: 32}];

const res = arr.filter(x => x.age <=30).map(x => x.name)
console.log(res)

使用Object.entries来键入嵌套有元素[index,value]的索引,然后在其上使用filter(),最后使用map()仅获得index

const arr = [{name: "Tom", age: 20}, {name: "Frank", age: 25}, {name: "Susie", age: 29}, {name: "Tina", age: 32}];

const res = Object.entries(arr).filter(([_,v]) => v.age <=30).map(x => +x[0])
console.log(res)

答案 1 :(得分:0)

使用Array.filter

let arr =[{name: "Tom", age: 20}, {name: "Frank", age: 25}, {name: "Susie", age: 29}, {name: "Tina", age: 32}];

let result = arr.filter(v => v.age <= 30);
console.log(result);

答案 2 :(得分:0)

是的filter是-并且在可读性方面有些夸张:

const dox = [{name: "Tom", age: 20}, {name: "Frank", age: 25}, {name: "Susie", age: 29}, {name: "Tina", age: 32}]

const arrayWithPeopleWhoForExampleAreLessOrEqualThen30 = 
dox.filter(peopleWhoForExampleAreLessOrEqualThen30)

function peopleWhoForExampleAreLessOrEqualThen30(doc){
 return doc.age <= 30
}