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"}]

總結

以上為個人經驗,希望能給大傢一個參考,也希望大傢多多支持WalkonNet。

推薦閱讀: