例如,我想用attributevalue
过滤此数组
如果我按蓝色进行搜索,那么所有衬衫都会给我一个蓝色,然后我对蓝色的织物棉进行搜索,然后给所有您知道的蓝色的cottob都进行搜索,例如flipkart,亚马逊
var myObject= [
{
"Product-name": "Shirt",
"product-price": "500",
"attributevalue": [
{ "color": "red" },
{"fabric": "cottton"}
]
},
{
"Product-name": "Samsung mobile",
"product-price": "15000",
"attributevalue":[
{"Ram": "4 GB"},
{"Network": "4G"},
{"Primary Camera": "8 MP"},
{"Internal Memory": "8 GB"}
]
}
]
答案 0 :(得分:1)
您可以结合使用filter
,for
和for...in
来做到这一点:
var myObject= [
{
"Product-name": "Shirt",
"product-price": "500",
"attributevalue": [
{ "color": "red" },
{"fabric": "cottton"}
]
},
{
"Product-name": "Samsung mobile",
"product-price": "15000",
"attributevalue":[
{"Ram": "4 GB"},
{"Network": "4G"},
{"Primary Camera": "8 MP"},
{"Internal Memory": "8 GB"}
]
}
]
const search = (arr, search) => {
return arr.filter(item => {
for (var i = 0; i < item.attributevalue.length; i++) {
for (var key in item.attributevalue[i]) {
if (item.attributevalue[i][key].toLowerCase() === search.toLowerCase()) {
return item;
}
}
}
})
}
console.log(search(myObject, 'red'))
答案 1 :(得分:1)
只要Array的filter
方法就能解决问题。
var myObject = [{
"Product-name": "Shirt",
"product-price": "500",
"attributevalue": [{
"color": "red"
}, {
"fabric": "cottton"
}]
}, {
"Product-name": "Samsung mobile",
"product-price": "15000",
"attributevalue": [{
"Ram": "4 GB"
}, {
"Network": "4G"
}, {
"Primary Camera": "8 MP"
}, {
"Internal Memory": "8 GB"
}]
}]
function findProduct(property, searchField) {
return myObject.filter((x) => {
const result = x.attributevalue.filter((y) => y[property] === searchField);
if (result.length) {
return x;
}
})
}
console.log(findProduct('Network', '4G'))
答案 2 :(得分:0)
尝试这样做:
const filterBy = (obj, attr, query) =>
obj.filter((prod) => prod.attributevalue && prod.attributevalue[attr] === query);
答案 3 :(得分:0)
这是一种支持多种过滤(多种键和值)以及多种支持键值检查的方法。
例程是:
var myObject = [
{
"Product-name": "Shirt",
"product-price": "500",
"attributevalue": [
{ "color": "red" },
{"fabric": "cottton"}
]
},
{
"Product-name": "Samsung mobile",
"product-price": "15000",
"attributevalue":[
{"Ram": "4 GB"},
{"Network": "4G"},
{"Primary Camera": "8 MP"},
{"Internal Memory": "8 GB"}
]
}
];
function filterBy(obj, searchBy) {
return obj.filter(item => {
const _assigned = Object.assign({}, ...item.attributevalue);
return Object.entries(searchBy).some(([k,v]) => {
return _assigned[k] && (typeof(v) === 'function' ? v.call(null, _assigned[k]) : _assigned[k] === v);
});
});
}
// Sample to filter by color and fabric.
console.log(filterBy(myObject, {
color: 'red',
fabric: (needle) => needle === 'cottton'
}));
// sample of callback filter that checks whether the "RAM" value exists and is, when lowercase, '4 gb'
console.log(
filterBy(myObject, {
Ram: (ram) => {
return ram && ram.toLowerCase() === '4 gb'
}
})
);