这篇文章主要介绍“js数组对象里面怎么获取某个属性值相等的对象”的相关知识,小编通过实际案例向大家展示操作过程,操作方法简单快捷,实用性强,希望这篇“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"}]