JavaScript 中 Object对象有没有快速查找对象中是否存在某个值的的方法,类似 Array的 arr.indexOf(value) !== -1
<!DOCTYPE html>
<html lang="en">
<head>
<script data-require="angularjs@1.5.5" data-semver="1.5.5" src="https://code.angularjs.org/1.5.5/angular.js"></script>
<meta charset="UTF-8">
<title>find in object</title>
</head>
<body>
<script>
var activities = [{
"act_name": "En promoci\u00f3n",
"product_ids": [41, 42]
}, {
"act_name": "En promoci\u00f3n",
"product_ids": [1]
}];
var product_id = 41;
// 如何用最短的JS代码来判断 product_id 是否是存在于 activities 任一一个的product_ids 中?
</script>
</body>
</html>
http://plnkr.co/edit/OZMKRgweqaGlDpUCM4B0?p=preview
伊谢尔伦2017-04-11 10:38:15
var o = {a: 'a', b: 'b', c: 'c'};
Object.keys(o).indexOf('a'); //0
Object.keys(o).indexOf('d'); //-1
--update--
看了评论,参考了stackoverflow,找到了一个稍稍拖鞋的方案
function hasValue(obj, key, value) {
return obj.hasOwnProperty(key) && obj[key] === value;
}
var test = [{name : "joey", age: 15}, {name: "hell", age: 12}]
console.log(test.some(function(boy) { return hasValue(boy, "age", 12); }));
天蓬老师2017-04-11 10:38:15
不太确定我理解是否正确,你是想找到数组里的对象的product_ids
包含了指定product_id
的对象集合?
那可以这么写:
var product_id = 41;
var activities = [
{
'act_id': 11,
'product_ids': [41, 42, 43, 44]
},
{
'act_id': 12,
'product_ids': [1]
}
];
var finds = activities.filter(act => act.product_ids.indexOf(product_id) > -1);
console.log(finds);//[ { act_id: 11, product_ids: [ 41, 42, 43, 44 ] } ]
修改:
鉴于你大概不在ES6
环境下执行代码,对ES6
也没什么概念,我改一个ES5
版本:
var finds = activities.filter(function(act) {
return act.product_ids.indexOf(product_id) > -1;
});