我有一些来自api的变量和JSON,可以说
var airlines = "Airasia";
var hotel = "Hyatt";
var tourType = "holiday";
var result = JSON.parse(data);
json结构如下:
[ { id: 1,
departure_month: 'September - November 2019',
program: '9 Days',
package_name: 'Example package 1',
tour_type: 'holiday',
airlines: 'Lion',
hotel: 'Hyatt'
},
{ id: 2,
departure_month: 'September - November 2019',
program: '15 Days',
package_name: 'Example package 2',
tour_type: 'pilgrimage',
airlines: 'Saudia',
hotel: 'pullman'
},
{ id: 3,
departure_month: 'September - November 2019',
program: '10 Days',
package_name: 'Example package 3',
tour_type: 'holiday',
airlines: 'Airasia',
hotel: 'Hyatt'
}
]
我想有效地搜索一个或多个参数(例如航空公司,酒店,tourType)是否存在,并且代码将返回与这些键匹配的json
例如,如果alirlines =“ Saudia”和hotel =“ pullman”,而其余为空,则代码将仅返回相应的参数
{ id: 2,
departure_month: 'September - November 2019',
program: '15 Days',
package_name: 'Example package 2',
tour_type: 'pilgrimage',
airlines: 'Saudia',
hotel: 'pullman'
}
答案 0 :(得分:1)
创建一个使用键数组的函数,并使用include和filter过滤这些值。
const json = [ { id: 1,
departure_month: 'September - November 2019',
program: '9 Days',
package_name: 'Example package 1',
tour_type: 'holiday',
airlines: 'Lion',
hotel: 'Hyatt'
},
{ id: 2,
departure_month: 'September - November 2019',
program: '15 Days',
package_name: 'Example package 2',
tour_type: 'pilgrimage',
airlines: 'Saudia',
hotel: 'pullman'
},
{ id: 3,
departure_month: 'September - November 2019',
program: '10 Days',
package_name: 'Example package 3',
tour_type: 'holiday',
airlines: 'Airasia',
hotel: 'Hyatt'
}
]
function searchJson(array, keys) {
return array.filter(item => {
const string = item && typeof item === 'object' && JSON.stringify(item).toLowerCase();
let match = false;
keys.forEach(key => {
if (string && string.includes(key.toLowerCase())) {
match = true;
} else {
match = false;
}
});
return match && item;
})
}
console.log(searchJson(json, ['holiday', 'Lion', 'Hyatt']))
答案 1 :(得分:0)
我想您只是希望找到内置的ES6运算符,该运算符可以让您指定搜索参数,并将返回它在数组中匹配的第一个元素。
请参阅此处: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/find
示例:
UIImage
如果要查找所有匹配项,则应使用result.filter而不是find。
https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/filter