[removed] How can I get all the keys and values of an object that begin with a specific string?

前端 未结 5 1668
一整个雨季
一整个雨季 2021-01-04 03:56

I am trying to get all the keys and values of an object that begin with imageIds.

My object appears as the following:

{
    title: \'fsd         


        
5条回答
  •  隐瞒了意图╮
    2021-01-04 04:46

    One also needs to use hasOwnProperty in conjunction with the for-in loop (not mentioned in most current previous answers).
    Reason is that the for-in loop will also go over the methods/properties that an object would inherit from the proto-type chain (should someone or some library have added custom stuff).

    So you are looking for something simple and reliable like this:

    function fetch(obj, str){
        var key, results = [];
        for(key in obj) obj.hasOwnProperty(key) 
                     && key.indexOf(str) === 0 
                     && results.push([ key, obj[key] ]);
        return results;
    }
    

    Note: you could also name this function 'getAllKeysAndValuesStartingWith' (or gakavsw should you work for the army haha).

    Usage:

    fetch(object, string) returns a simple (to loop over) array with found results,
    so var my_results = fetch(testObj, 'imageId'); would give the following output:

    [ //array of arrays
      ['imageIds', '/uploads/tmp/image-3.png']
    , ['imageIdsZh', '']                               /* 
    , [key, value]           and more if it finds them */
    ]
    

    Working jsfiddle here.

    Naturally one could also push just the values: results.push(obj[key])
    I would recommend against returning an object ( (results[key]=obj[key]) ) since the array is easier to work with in this case.

    Hope this helps!

提交回复
热议问题