Getting the values for a specific key from all objects in an array

后端 未结 7 1987
醉酒成梦
醉酒成梦 2020-12-15 04:32

I\'m running an express.js app that has a few apis feeding data to dropdown boxes. The data returned is in the form:

  [
    {
        key: \'blah\',
                


        
7条回答
  •  一向
    一向 (楼主)
    2020-12-15 04:51

    You could extract the values via map, and form them into a regex to match values against.

    Example: http://repl.it/X0V

    var items=
    [
        {
            key: 'blah',
            value: 'Blah Blah'
        },
        {
            key: 'foo',
            value: 'Foos'
        },
        {
            key: 'bar',
            value: 'Bars'
        },
        {
            key: 'baz',
            value: 'Bazingo'
        }
    ];
    
    var toReg = items.map(function(obj){
        return obj.key; 
    }).join('|');
    var regex = new RegExp('^('+ toReg +')$');
    
    //To test the regex
    var itemsToTest = ['blah', 'Pies', 'foo', 'Bazingo'];
    itemsToTest.forEach(function(key){
       if(regex.test(key)){
           console.log(key);
       }
    });
    

提交回复
热议问题