来自获取请求的回复:
[
{
id: 234,
resturant_name : "dish",
cusions : {1:"italian", 2 : "indian", 3: "foo"},
address : NYI
},
{
id: 235,
resturant_name : "kebab",
cusions : {1:"china", 2 : "indian", 3: "american"},
address : NYI
},
{
id: 236,
resturant_name : "itrup",
cusions : {1:"italian", 2: "american"},
address : NYI
}
]
我想过滤一个具有“美国”类型的cusions数组的数组,从上面的对象中我期待回应
{
id: 235,
resturant_name : "kebab",
cusions : {1:"china", 2 : "indian", 3: "american"},
address : NYI
},
{
id: 236,
resturant_name : "itrup",
cusions : {1:"italian", 2: "american"},
address : NYI
}
过滤后^^^
答案 0 :(得分:1)
您可以将Array#filter
与Object.keys
和Array#some
结合使用来检查所需的cuisine
。
var data = [{ id: 234, restaurant: "dish", cuisines: { 1: "italian", 2: "indian", 3: "foo" }, address: "NYI" }, { id: 235, restaurant: "kebab", cuisines: { 1: "china", 2: "indian", 3: "american" }, address: "NYI" }, { id: 236, restaurant: "itrup", cuisines: { 1: "italian", 2: "american" }, address: "NYI" }],
cuisine = 'american',
result = data.filter(function (a) {
return Object.keys(a.cuisines).some(function (k) {
return a.cuisines[k] === cuisine;
});
});
console.log(result);
.as-console-wrapper { max-height: 100% !important; top: 0; }
ES6
var data = [{ id: 234, restaurant: "dish", cuisines: { 1: "italian", 2: "indian", 3: "foo" }, address: "NYI" }, { id: 235, restaurant: "kebab", cuisines: { 1: "china", 2: "indian", 3: "american" }, address: "NYI" }, { id: 236, restaurant: "itrup", cuisines: { 1: "italian", 2: "american" }, address: "NYI" }],
cuisine = 'american',
result = data.filter(a => Object.values(a.cuisines).includes(cuisine));
console.log(result);
.as-console-wrapper { max-height: 100% !important; top: 0; }
答案 1 :(得分:1)
其中一种方法:
var arr = [
{
id: 234,
resturant_name : "dish",
cusions : {1:"italian", 2 : "indian", 3: "foo"},
address : 'NYI'
},
{
id: 235,
resturant_name : "kebab",
cusions : {1:"china", 2 : "indian", 3: "american"},
address : 'NYI'
},
{
id: 236,
resturant_name : "itrup",
cusions : {1:"italian", 2: "american"},
address : 'NYI'
}
];
var res = arr.filter(x=> {
return JSON.stringify(x.cusions).indexOf('american') >=0;
});
console.log(res);