我试图创建一个查看对象数组(第一个参数)的函数,并返回一个具有匹配属性和值对(第二个参数)的所有对象的数组。如果要包含在返回的数组中,源对象的每个属性和值对都必须存在于集合中的对象中。
例如,如果第一个参数是
[{
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" });
答案 0 :(得分:1)
使用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);
答案 1 :(得分:1)
我有两种可能的解决方案
示例:
var result = _.filter(array, {last: "Capulet"});
var arr = [
{
first: "Romeo",
last: "Montague"
},
{
first: "Mercutio",
last: null
},
{
first: "Tybalt",
last: "Capulet"
}];
var res = _.filter(arr, {last: "Capulet"});
console.log(res);
&#13;
<script src="https://cdnjs.cloudflare.com/ajax/libs/lodash.js/4.1.0/lodash.js"></script>
&#13;
答案 2 :(得分:0)
如果您不想从头开始编写功能以满足您的要求,那么UnderscoreJS可能会帮您解决问题。查看下面的链接。
_.where(list, properties) in underscorejs library
var list = [{ first: "Romeo", last: "Montague" }, { first: "Mercutio", last: null }, { first: "Tybalt", last: "Capulet" }];
console.log(_.where(list, { last: "Capulet" })); // prints on console
// [{ first: "Tybalt", last: "Capulet" }]
答案 3 :(得分:0)
你可以尝试这个
function where(collection, source) {
for (var i = 0; i < collection.length; i++){
var found = true;
for (var name in source){
//If one of the property does not match, do not return the object
if (collection[i][name] != source[name]){ found = false; }
}
if (found) {
//If you want the object
return collection[i];
//If you want the object in an array
return [collection[i]];
}
}
}