在对象数组中查找整个对象

时间:2016-11-30 16:22:57

标签: javascript jquery arrays

如何在 Array1 中找到 Array2 。我一直在使用 $。inArray()方法或 indexOf(),但它返回false但语句为真。

var array1 = [{
    h: 1480508328,
    rid: 16,
    sid: 2
  }, {
    h: 87542,
    rid: 18,
    sid: 9
  }
];
var array2 = {
  h: 1480508328,
  rid: 16,
  sid: 2
};
//test if array2 exist in array1
if ($.inArray(array2, array1) > 0) {
  console.log('Object is in array');
} else {
  console.log('Object is not in array');
}

请帮忙。谢谢

3 个答案:

答案 0 :(得分:4)

您可以迭代数组并使用给定对象的长度检查属性的长度,并检查每个值。



var array = [{ h: 1480508328, rid: 16, sid: 2 }, { h: 87542, rid: 18, sid: 9 }],
    object = { h: 1480508328, rid: 16, sid: 2 },
    found = array.some(function (a) {
        var keys = Object.keys(a);
        return keys.length === Object.keys(object).length && keys.every(function (k) {
            return a[k] === object[k];
        });
    });
  
console.log(found);






var array = [{ h: 87542, rid: 18, sid: 9 }, { h: 1480508328, rid: 16, sid: 2 }],
    object = { h: 1480508328, rid: 16, sid: 2 },
    found = array.some(function (a) {
        var keys = Object.keys(a);
        return keys.length === Object.keys(object).length && keys.every(function (k) {
            return a[k] === object[k];
        });
    });
  
console.log(found);




答案 1 :(得分:3)

使用Array.prototype.every检查数组的每个对象属性是否匹配 - 现在使用Array.prototype.some检查对象是否存在于数组中。

见下面的演示:



var array1=[{h:1480508328,rid:16,sid:2},{h:87542,rid:18,sid:9}];
var object={h:1480508328,rid:16,sid:2}

var result = array1.some(function(e){
  return Object.keys(object).length === Object.keys(e).length && Object.keys(e).every(function(k){
    return k in object && e[k] === object[k];
  });
});

console.log(result);




答案 2 :(得分:1)

您可以对其进行字符串化并检查是否相等

var array1 = [{
    h: 1480508328,
    rid: 16,
    sid: 2
  }, {
    h: 87542,
    rid: 18,
    sid: 9
  }
];
var array2 = {
  h: 1480508328,
  rid: 16,
  sid: 2
};

var dat1 = JSON.stringify(array2);
array1.forEach(function(item){
    if(JSON.stringify(item) === dat1){
        console.log(dat1)
    } else {
        console.log('Not match')
    }
});

JSFIDDLE