javascript Node 对象数组中的 IndexOf

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/14016476/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-10-26 20:29:22  来源:igfitidea点击:

IndexOf in arrays of objects in Node

javascriptnode.js

提问by piggyback

I am not sure on the use of indexOf in arrays of objects

我不确定在对象数组中使用 indexOf

The code which is not working is:

不起作用的代码是:

if (res.locals.company.companies.indexOf(req.query.companyId) >= 0) return next()

The if condition will always return false.

if 条件将始终返回 false。

I also tested in console and it is actually wrong:

我也在控制台中测试过,它实际上是错误的:

>> var zio = { __v: 1,
  _id: '50bc0238049a1ff10b000001',
  companies: 
   [ { _id: '50bc01938f164ee80b000001', name: 'Test' },
     { _id: '50bc01ac4e860ee90b000001', name: 'zio' } ],
}

>> zio.companies.indexOf("50bc01938f164ee80b000001")
-1

whereas it should be true.

而它应该是真的。

Should I use any mysterious underscore utility ?

我应该使用任何神秘的下划线实用程序吗?

UPDATE/Clarification:my aim is just to check if 50bc01938f164ee80b000001 exists in one of the ids, I don't need to know where it actually is. This is very performance critical!

更新/澄清:我的目的只是检查 50bc01938f164ee80b000001 是否存在于其中一个 id 中,我不需要知道它实际上在哪里。这是非常关键的性能!

Nodejs solutions or tips would be amazing!

Nodejs 解决方案或技巧会很棒!

回答by jAndy

It's not wrong. That Arraydoes not contain a Stringlike that, but only two Object references. Hence, the result is correctly -1.

这没有错。该Array不包含这样的String,但只有两个Object 引用。因此,结果是正确的-1

To get the index from the Object referencecontaining the searched string value, we could go like

要从包含搜索字符串值Object 引用中获取索引,我们可以像

var index;
zio.companies.some(function( obj, idx ) {
    if( obj._id === '50bc01938f164ee80b000001' ) {
        index = idx;
        return true;
    }
});

console.log('index is: ', index);


Based on your ninja edit, if you just want to know whether or not an object ref holding a specific idis contained by that array, use it like

根据您的 ninja 编辑,如果您只想知道该数组是否包含持有特定id的对象引用,请使用它

var check = zio.companies.filter(function( obj ) {
    return obj._id === '50bc01938f164ee80b000001';
});

if( check.length ) {
    console.log('yep');
} else {
    console.log('nope');
}


Second edit: If you are really and only after performance, you probably don't want to have any function call overheadin any search. I'd use something like

第二次编辑:如果您真的并且只关注性能,您可能不希望在任何搜索中都有任何函数调用开销。我会使用类似的东西

function inObject(arr, search) {
    var len = arr.length;
    while( len-- ) {
        if(arr[len]._id === search)
           return true;
    }
}

if( inObject( zio.companies, 'AAA' ) ) {
}

That code outclasses any snippet provided here by a few magnitudes. See Here

该代码比此处提供的任何代码段高出几个数量级。看这里

回答by Corbin

You'll need to loop over the elements and check for the _idbeing equal.

您需要遍历元素并检查_id是否相等。

indexOfchecks for strict equality, and those objects are of course not equal to that string. (It's the same logic as "hello" === {foo: "hello"}. That will always be false.)

indexOf检查严格相等,这些对象当然不等于该字符串。(它与 的逻辑相同"hello" === {foo: "hello"}。那总是错误的。)

I'm sure with node there's some fancy way to do that, but the bare-JS way is:

我确定使用 node 有一些奇特的方法可以做到这一点,但裸 JS 方法是:

var i,
    arr = [{foo: 'bar'}, {foo: 'baz'}],
    idx = -1;
for (i = 0; i < arr.length; ++i) {
    if (arr[i].foo === 'bar') {
        idx = i;
        break;
    }
}

You could also easily turn that into a function:

你也可以很容易地把它变成一个函数:

function indexOf(arr, pred) {
    for (var i = 0; i < arr.length; ++i) {
        if (pred(arr)) {
            return i;
        }
    }
    return -1;
}

That would give you a lot more verbose usage though (and a bit worse performance), but it might also be a bit more flexible if you find yourself needing to do it often.

虽然这会给您带来更多冗长的用法(并且性能会更差),但如果您发现自己需要经常这样做,它也可能更加灵活。

console.log(indexOf(arr, function(elem) { return elem.foo === 'bar'; });

回答by Yogendra Singh

Your companiesseems to be an array of objects (not ids), which has Idas one of the attributes. indexOffunction is used to find the index of the matching element. Since you are passing an ID value to search the index, its not finding it as an element on the array hence returning false.

companies似乎是一组对象(不是 id),它具有Id其中一个属性。indexOf函数用于查找匹配元素的索引。由于您正在传递一个 ID 值来搜索索引,因此它没有将其作为数组中的元素找到,因此返回 false。

To fix the problem, you have two options:

要解决此问题,您有两种选择:

  1. Iterate the companies element compare the ID value, if matched return true otherwise false.

  2. Use the object with desired id in as argument in the indexOffunction. If value is greater than -1, return true otherwise false.

  1. 迭代公司元素比较 ID 值,如果匹配返回 true 否则返回 false。

  2. 在函数中使用具有所需 id 的对象作为参数indexOf。如果 value 大于 -1,则返回 true,否则返回 false。

回答by 0x499602D2

.indexOfis returning the correct output; your array doesn't have an element with that string. In fact, it's an array holding two object literals. You don't need .indexOffor objects, instead we must make our own function:

.indexOf正在返回正确的输出;您的数组没有带有该字符串的元素。事实上,它是一个包含两个对象字面量的数组。您不需要.indexOf对象,而是我们必须创建自己的函数:

 var inObject = function( object, val ) {

     for (var i in object) { if ( object.hasOwnProperty(i) ) {

             if ( obj[i] === val ) {

                 return true;
             }

         }

     }
     return false;
 };

>>> inObject( zio.companies[0], '50bc01938f164ee80b000001' );
    : true