我正在尝试创建一个函数,该函数查看对象数组(第一个参数)并返回具有匹配属性和值对(第二个参数)的所有对象的数组。如果要包含在返回的数组中,源对象的每个属性和值对都必须存在于集合中的对象中。
例如,如果第一个参数是
[{
first: "Romeo",
last: "Montague"
}, {
first: "Mercutio",
last: null
}, {
first: "Tybalt",
last: "Capulet"
}]
,第二个参数是 { last: "Capulet"}
,那么您必须从数组中返回第三个对象(第一个参数),因为它包含属性及其值,即作为第二个参数传递。
到目前为止,这是我尝试过的,但我要么在新数组中什么也没得到,要么在插入的所有对象中都没有得到:
function where(collection, source) {
var arr = [];
// iterating through the properties in course
for (var name in source){
// if the name from source is found in collection
for (var i =0; i<collection.length; i++) {
if (collection[i].hasOwnProperty(name))
{
// push the object onto the array?????
arr.push(collection[i]);
console.log(collection[i]);
}
}
}
return arr;
}
where([{ first: "Romeo", last: "Montague" }, { first: "Mercutio", last: null }, { first: "Tybalt", last: "Capulet" }], { last: "Capulet" });
最佳答案
使用Array.prototype.filter和 Array.prototype.every :
如果我理解正确的话,你想要这样的东西;
var src = {last: "Capulet"};
var arr = [
{
first: "Romeo",
last: "Montague"
},
{
first: "Mercutio",
last: null
},
{
first: "Tybalt",
last: "Capulet"
}];
var newArr = arr.filter(function(item) {
if(Object.keys(src).every(function(k){
return src.hasOwnProperty(k) && item.hasOwnProperty(k) && src[k] === item[k]}))
{
return item;
}
});
console.log(newArr);
关于javascript - JavaScript 中将对象从对象数组插入数组,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/35124803/