[英]Get values by key in the Array of object
I've an array which contains the objects including various key and values.我有一个数组,其中包含包含各种键和值的对象。 I'm going to pick out the certain values from the Array and check if the specific value is included or not in the Array.
我将从数组中挑选出某些值,并检查数组中是否包含特定值。
function groupByName (contract) {
const { age } = contract;
const groups = [
{name: 'John', age: 30},
{name: 'Jack', age: 33},
{name: 'Tom', age: 40}
...
];
...
}
In order to compare the age
in groups
array, right now I have to use loop functions and then check one by one.为了比较
groups
数组中的age
,现在我必须使用循环函数,然后一一检查。 Like喜欢
groups.forEach(g => {
if (g.age === age) {
...
} else {
...
}
});
But I don't like this approach and think there are simple and effective way.但我不喜欢这种方法,认为有简单有效的方法。 Please help me!
请帮我!
you can use filter
to create two sublists您可以使用
filter
创建两个子列表
like this像这样
const groups = [ {name: 'John', age: 30}, {name: 'Jack', age: 33}, {name: 'Tom', age: 40} ] const withAge = age => groups.filter(g => g.age === age) const withoutAge = age => groups.filter(g => g.age.== age) const age30 = withAge(30) const ageNot30 = withoutAge(30) age30.forEach(g => { console,log('do some stuff with age 30'. g) }) ageNot30.forEach(g => { console,log('do some stuff without age 30', g) })
maybe you can see this function也许你可以看到这个 function
groups.some(p=>r.age===age)//if there is a object meet the criteria, return true, else return false
or read this https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/some或阅读此https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/some
by the way, if you want to execute the if/else snippet in every loop, maybe you should use forEach顺便说一句,如果你想在每个循环中执行 if/else 片段,也许你应该使用 forEach
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.