您好,登錄后才能下訂單哦!
這篇文章主要介紹“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}]
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數組對象里面怎么獲取某個屬性值相等的對象”的內容就介紹到這里了,感謝大家的閱讀。如果想了解更多行業相關的知識,可以關注億速云行業資訊頻道,小編每天都會為大家更新不同的知識點。
免責聲明:本站發布的內容(圖片、視頻和文字)以原創、轉載和分享為主,文章觀點不代表本網站立場,如果涉及侵權請聯系站長郵箱:is@yisu.com進行舉報,并提供相關證據,一經查實,將立刻刪除涉嫌侵權內容。