javascript - 如何过滤多维数组对象
问题描述
我想过滤这个数组attributevalue
,例如,如果我按蓝色进行搜索,那么所有衬衫都给我蓝色,然后我搜索蓝色的织物棉然后给所有蓝色的棉布,你知道搜索像 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"}
]
}
]
解决方案
您可以结合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'))
推荐阅读
- asp.net-mvc - 如何使用 mvc 控制器发送自定义 http 400 错误消息?
- function - 剪辑中的切换功能
- python - 如何在传递给模板之前在 Django ListView 中编辑输出
- c++ - 分段错误 C++ 程序
- javascript - 具有 prevState 比较的 componentDidUpdate 正在处理备用触发器
- javascript - 计算器未捕获的类型错误无法将属性“值”设置为空
- algorithm - 通过用另一个函数替换一个递归来优化排序算法
- c - 使用在 C 中执行子字符串的函数时字符串解析失败
- laravel - 为什么 Eloquent 模型“引导”方法在 Laravel 7.x 上没有触发?
- javascript - 获取当前电子邮件的 URL 谷歌脚本