[英]how to filter multi dimensional array object
我想通過attributevalue
過濾這個數組,例如,如果我按藍色搜索,然后所有襯衫都給我藍色,然后我搜索藍色的織物棉,然后給所有藍色的 cottob 你知道的搜索方式,如flipkart、amazon
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"}
]
}
]
你可以結合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'))
僅 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'))
嘗試這樣做:
const filterBy = (obj, attr, query) =>
obj.filter((prod) => prod.attributevalue && prod.attributevalue[attr] === query);
這是一種支持多重過濾(多個鍵和值)和多重支持鍵值檢查的方法。
套路是:
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' } }) );
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.