如何使用另一个对象中的值过滤对象数组?

时间:2018-10-01 13:46:57

标签: javascript arrays object

我想编写一个函数,该函数将具有某些键值对的对象数组作为第一个参数。还有一个具有键值对作为第二个参数的对象。

该函数应检查是否在第一个参数的对象数组中找到了第二个参数的键值对。

如果是,它将返回具有匹配的名称和值对的对象数组。

例如,如果我有一个对象数组(第一个参数):

[{name: "Peter", age: 21}, {name: "Kate", age: 18}, {name: "Tihon", age: 17}, {name: "Poopy", age: 17}]

作为第二个参数:

{age: 17}

它应该返回:

[{name: "Tihon", age: 17}, {name: "Poopy", age: 17}]

由于匹配值age

这是我想出的,但不知道要放在for...in循环中的内容:

   function checkTheName(list, check) {
     let newArr = [];
     for(let i = 0; i < list.length; i++){
        for(let key in list[i]){
            // Stuck here
        }
     }
     return newArr;
   }

6 个答案:

答案 0 :(得分:4)

您可以使用filterevery方法进行操作。

let a = [{name: "Peter", age: 21}, {name: "Kate", age: 18}, {name: "Tihon", age: 17}, {name: "Poopy", age: 17}]
let b = {age: 17}

function checkTheName(list, check) {
  return list.filter(o => Object.keys(check).every(k => {
    return (k in o) && check[k] == o[k]
  }))
}

console.log(checkTheName(a, b))

答案 1 :(得分:1)

带有Array.prototype.filterArray.prototype.every的简单ES6版本:

const data = [{name: "Peter", age: 21}, {name: "Kate", age: 18}, {name: "Tihon", age: 17}, {name: "Poopy", age: 17}];

const fObj = {age: 17};

const filtred = data.filter(item =>
    Object.keys(fObj).every(k => item.hasOwnProperty(k) && item[k] === fObj[k])
);

console.log(filtred);

答案 2 :(得分:0)

您可以遍历数组并测试该属性:

function checkTheName(check, list){
    for (var i=0; i < myArray.length; i++) {
        if (myArray[i].name === nameKey) {
            return myArray[i];
        }
    }
}

var array =[{name: "Peter", age: 21}, {name: "Kate", age: 18}, {name: "Tihon", 
age: 17}, {namenter code heree: "Poopy", age: 17}]
;

var resultObject = checkTheName( array,"string 1");

答案 3 :(得分:0)

使用过滤器遍历数组。

function findByAge(myArr, obj){
    myArr.filter( (item) => {
       if(obj.age === item.age){
         return item
       }
    })
}

这将返回一个仅包含您要查找的数组项的数组。

您可以在下一行中调用它。由于该函数返回一个新数组。我们需要给新数组起一个名字(在本例中为newArray)。

var newArray = findByAge(myArr, obj)

答案 4 :(得分:0)

您需要放置一个if条件,将age对象的check值与age对象的list值进行比较。如果两个值相等,则在newArr中推送对象。

let list = [{ name: "Peter", age: 21 }, { name: "Kate", age: 18 }, { name: "Tihon", age: 17 }, { name: "Poopy", age: 17 }], 
    check = { age: 17 };
function checkTheName(list, check) {
  let newArr = [];
  for (let i = 0; i < list.length; i++) {
    if (list[i].age == check.age) {
      newArr.push(list[i]);
    }
  }
  return newArr;
}
console.log(checkTheName(list, check));

或者,您也可以使用array#filter

let list = [{name: "Peter", age: 21}, {name: "Kate", age: 18}, {name: "Tihon", age: 17}, {name: "Poopy", age: 17}],
    check = {age: 17},
    result = list.filter(o => o.age === check.age);
console.log(result);

答案 5 :(得分:0)

var filterobj ={age:17};
var data=[{name: "Tihon", age: 17}, {name: "Poopy", age: 17}]
 var newArray = data.filter(function (el) {
 return el.age ==filterobj.age;
}