【问题标题】:JS use indexOf on an array of objectsJS 在对象数组上使用 indexOf
【发布时间】:2019-08-22 23:26:18
【问题描述】:

我想在对象数组上使用 indexOf()。例如:

var arr;
var arr[0] = {a: 1, b: 2};
var arr[1] = {a: 1, b: 3};
var obj = {a: 1, b: 2};

console.log(arr.indexOf(obj));

这将打印 -1 因为 arr[0] 不等于 obj。我怎样才能使这项工作(即打印 0)?

【问题讨论】:

  • 它不起作用,因为你不能直接比较对象。
  • 您正在比较对象实例,但在这里您有两个不同的对象实例,它们恰好具有相同的属性。 obj = arr[0]; console.log(arr.indexOf(obj));0

标签: javascript arrays object object-equality


【解决方案1】:

您必须比较属性。这样的事情会起作用:

var arr = [];
arr[0] = {a: 1, b: 2};
arr[1] = {a: 1, b: 3};

console.log(arr.findIndex(o => o.a === 1 && o.b === 2));
//0
console.log(arr.findIndex(o => o.a === 1 && o.b === 3));
//1

【讨论】:

    【解决方案2】:

    array.findIndex() 函数将返回比较函数结果为true 的第一个值的索引。我有一个函数可以用来比较两个对象是否相等,可以在这个例子中使用。

    var obj = {a: 1, b: 2};
    var arr = [];
    arr[0] = {a: 1, b: 2};
    arr[1] = {a: 1, b: 3};
    
    var idx = arr.findIndex(element => areObjsEqual(element,obj));
    console.log(`The index is: ${idx}`);
    
    //Function to check if two js objects are equal
    function areObjsEqual(a, b) {
        // Create arrays of property names
        var aProps = Object.getOwnPropertyNames(a);
        var bProps = Object.getOwnPropertyNames(b);
    
        // If number of properties is different,
        // objects are not equivalent
        if (aProps.length != bProps.length) { return false;}
        
        //loop through the object and compare the property values
        for (var i = 0; i < aProps.length; i++) {
            var propName = aProps[i];
            // If values of same property are not equal,
            // objects are not equivalent
            if (a[propName] !== b[propName]) {
                return false;
            }
        }
        // If we made it this far, objects
        // are considered equivalent
        return true;
    }

    【讨论】:

      【解决方案3】:

      我创建了一个similar 函数,它可以比较几乎所有的东西,不久前:

      function similar(needle, haystack, exact){
        if(needle === haystack){
          return true;
        }
        if(needle instanceof Date && haystack instanceof Date){
          return needle.getTime() === haystack.getTime();
        }
        if(!needle || !haystack || (typeof needle !== 'object' && typeof haystack !== 'object')){
          return needle === haystack;
        }
        if(needle === null || needle === undefined || haystack === null || haystack === undefined || needle.prototype !== haystack.prototype){
          return false;
        }
        var keys = Object.keys(needle);
        if(exact && keys.length !== Object.keys(haystack).length){
          return false;
        }
        return keys.every(function(k){
          return similar(needle[k], haystack[k]);
        });
      }
      var obj1 = {a:1, b:[5, 'word'], c:{another:'cool', neat:'not', num:1}, d:'simple string'};
      var obj2 = {a:1, b:[5, 'word'], c:{another:'cool', neat:'not', num:1}, d:'simple string'};
      console.log(similar(obj1, obj2, true)); // true for exact match
      obj2.newProp = 'new value'; // extra haystack prop added
      console.log(similar(obj1, obj2, true)); // true for exact - result is false here
      console.log(similar(obj1, obj2)); // not exact - obj1 properties and values are in obj2

      当然可以让similarhaystack 中找到similarIndexneedle (任何东西) (任何东西的数组),像这样:

      function similar(needle, haystack, exact){
        if(needle === haystack){
          return true;
        }
        if(needle instanceof Date && haystack instanceof Date){
          return needle.getTime() === haystack.getTime();
        }
        if(!needle || !haystack || (typeof needle !== 'object' && typeof haystack !== 'object')){
          return needle === haystack;
        }
        if(needle === null || needle === undefined || haystack === null || haystack === undefined || needle.prototype !== haystack.prototype){
          return false;
        }
        var keys = Object.keys(needle);
        if(exact && keys.length !== Object.keys(haystack).length){
          return false;
        }
        return keys.every(function(k){
          return similar(needle[k], haystack[k]);
        });
      }
      function similarIndex(needle, haystack, exact){
        for(var i=0,l=haystack.length; i<l; i++){
          if(similar(needle, haystack[i], exact)){
            return i;
          }
        }
        return -1;
      }
      var objArray = [{a:1, b:[5, 'wtf'], c:{another:'cool', neat:'not', num:1}, d:'simple string'}, {a:1, b:[5, 'word'], c:{another:'cool', neat:'not', num:1}, d:'simple string'}, {a:1, b:[5, 'word'], c:{another:'cool', neat:'not', num:4}, d:'simple string'}];
      var testObj = {a:1, b:[5, 'word'], c:{another:'cool', neat:'not', num:1}, d:'simple string'};
      console.log(similarIndex(testObj, objArray, true)); // exact - index is 1 in this case
      objArray[1].newProp = 'new value'; // haystack array element 1 gets new property and value
      console.log(similarIndex(testObj, objArray, true)); // exact - -1 result here
      console.log(similarIndex(testObj, objArray)); // not exact - index 1

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2012-01-08
        • 1970-01-01
        • 2014-07-31
        • 2019-04-29
        • 2017-11-02
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多