首頁  >  問答  >  主體

angular.js - javascript 中Object 查找值存在方法,类似 array.indexOf(value) !== -1

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

天蓬老师天蓬老师2727 天前443

全部回覆(2)我來回復

  • 伊谢尔伦

    伊谢尔伦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); }));

    回覆
    0
  • 天蓬老师

    天蓬老师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;
    });

    回覆
    0
  • 取消回覆