我有一个对象数组,需要查找对象数组是否包含任何属性的给定值? (它可以用于任何财产)。
例如:
[
{product_name: "iphone 7s " , cost: "122" , type: "product" },
{name: "John Snow " , email: "jon_snow@got.com" , type: "contact"},
{seller_name: "John Smith " , brand: "Xbrand" , type: "seller"}
];
我需要一个函数来返回值“John”存在的最后两个对象。
答案 0 :(得分:3)
您可以过滤数组,检查对象的值是否包含所需的字符串。
var data = [{ product_name: "I phone 7s ", cost: "122", type: "product" }, { name: "Joh Snow ", email: "jon_snow@got.com", type: "contact" }, { seller_name: "Joh Smith ", brand: "Xbrand", type: "seller" }],
result = data.filter(o => Object.values(o).some(s => s.includes('Joh')));
console.log(result);
答案 1 :(得分:0)
您可以做的是遍历对象数组,并检查属性值是否包含您的文本。然后,您可以将其添加到数组中,并使用slice从该数组中获取最后2个。
例如:
var objects = [
{product_name: "iphone 7s ", cost: "122", type: "product"},
{name: "John Snow ", email: "jon_snow@got.com", type: "contact"},
{seller_name: "John Smith ", brand: "Xbrand", type: "seller"}
];
function getObjectsContaining(coll, value) {
var results = [];
for (var i = 0; i < coll.length; i++) {
var obj = coll[i];
for (var property in obj) {
if (obj.hasOwnProperty(property) && obj[property].indexOf(value) !== -1) {
results.push(obj);
}
}
}
return results.slice(-2);
}
console.log(getObjectsContaining(objects, "John"));
&#13;