js数组对象里面如何获取某个属性值相等的对象

js数组对象里面获取某个属性值相等的对象

例:

var outArr=[
	{"name":"张三","id":1,age:18},
	{"name":"李四","id":2,age:19},
	{"name":"王五","id":3,age:18},
	{"name":"小红","id":4,age:20},
	{"name":"小明","id":5,age:17},
	{"name":"小白","id":6,age:18}
];
var newArr = outArr.filter(function (obj) {
    return obj.age== 18;
});
console.log(newArr);    // [{"name":"张三","id":1,age:18},{"name":"王五","id":3,age:18},{"name":"小白","id":6,age:18}]

js获取两个数组及数组对象中相同和不相同的值

1、获取两个数组中相同的元素

var arr1 = [0,1,2,3,4,5];
var arr2 = [0,4,6,1,3,9];
function getArrEqual(arr1, arr2) {
        let newArr = [];
        for (let i = 0; i < arr2.length; i++) {
            for (let j = 0; j < arr1.length; j++) {
                if(arr1[j] === arr2[i]){
                    newArr.push(arr1[j]);
                }
        }
     }
     return newArr;
}
console.log(getArrEqual(arr1, arr2));
//[0, 4, 1, 3]

2、获取两个数组中不相同的元素

var arr1 = [0,1,2,3,4,5];
var arr2 = [0,4,6,1,3,9];
function getArrDifference(arr1, arr2) {
    return arr1.concat(arr2).filter(function(v, i, arr) {
         return arr.indexOf(v) === arr.lastIndexOf(v);
    });
}
console.log(getArrDifference(arr1,arr2));
 
 // [2, 5, 6, 9]

3、获取两个数组对象中相同的值

function getArrDifSameValue(arr1,arr2){
    var result = [];
    for(var i = 0; i < arr2.length; i++){
        var obj = arr2[i];
        var id = obj.id;
        var isExist = false;
        for(var j = 0; j < arr1.length; j++){
            var aj = arr1[j];
            var n = aj.id;
            if(n == id){
                isExist = true;
                break;
            }
        }
        if(isExist){
            result.push(obj);
        }
    }
    return result;
}
 
var arr1 = [ {"id": "A"},{"id": "B"}];
var arr2 = [ {"id": "A"}, {"id": "B"},{"id": "C"}];
console.log(getArrDifSameValue(arr1,arr2));

4、获取两个数组对象中不相同的值 

function getArrDifSameValue(arr1,arr2){
    var result = [];
    for(var i = 0; i < arr2.length; i++){
        var obj = arr2[i];
        var id = obj.id;
        var isExist = false;
        for(var j = 0; j < arr1.length; j++){
            var aj = arr1[j];
            var n = aj.id;
            if(n == id){
                isExist = true;
                break;
            }
        }
        if(!isExist){
            result.push(obj);
        }
    }
    return result;
}
 
var arr1 = [ {"id": "A"},{"id": "B"}];
var arr2 = [ {"id": "A"}, {"id": "B"},{"id": "C"}];
console.log(getArrDifSameValue(arr1,arr2));
// [{"id": "C"}]

总结

以上为个人经验,希望能给大家一个参考,也希望大家多多支持脚本之家。

你可能感兴趣的:(js数组对象里面如何获取某个属性值相等的对象)