简体   繁体   English

根据属性过滤对象数组

[英]Filter an object array based on the property

The data I have stored is in a 2d Array. 我存储的数据在2d数组中。

One element of looks like below. 的一个元素如下所示。 (not an assignment operator) (不是赋值运算符)

someObjArray[5] === [{lastname:"foo", firstname:"bar", grade:10, userId:"foobar1234"},...]

For the particular above variable I want to filter on userId I am attempting to do so like this. 对于上面的特定变量,我想像这样对userId进行过滤。

var test = stuArray[5].filter(function(item) {
    return item['userId'];
});

Resulting in: 导致:

test === [{lastname:"foo", firstname:"bar", grade:10, userId:"foobar1234"},...]

Where the desired results are 预期结果在哪里

test === ["foobar1234",...]

I have also tried using a dot operator with the same results. 我也尝试过使用点运算符获得相同的结果。

I don't think filter is what you're looking for here. 我不认为过滤器是您在这里寻找的东西。

The function (non-anonymous in your case but you can also use anonymous functions) that you are passing into your filter method needs to return a true or a false. 传递给filter方法的函数(在您的情况下为非匿名函数,但您也可以使用匿名函数)需要返回true或false。 This is how the method "filters" your array - it gives you back an array whose elements pass the filter, or return true when passed as arguments into filter's function. 这就是方法“过滤”数组的方式-它给您返回一个数组,其元素通过过滤器,或者作为参数传递给过滤器函数时返回true。

Note that this does not change the original array. 请注意,这不会更改原始数组。

What you should use instead is the very similar map() function. 您应该使用的是非常相似的map()函数。

Note that map(), just like filter(), does not change the original array. 请注意,就像filter()一样,map()不会更改原始数组。

You can do it like this: 您可以这样做:

var someObjArray = [{lastname:"foo", firstname:"bar", grade:10, userId:"foobar1234"}];
console.log(someObjArray.map(s => s.userId));

Online demo (jsFiddle) 在线演示(jsFiddle)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM