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

前端 未结 5 1695
一整个雨季
一整个雨季 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条回答
  •  猫巷女王i
    2021-01-04 04:24

     // json to be searched
    var data = {
        title: 'fsdfsd',
        titleZh: 'fsdfsd',
        body: 'fsdf',
        bodyZh: 'sdfsdf',
        imageIds: '/uploads/tmp/image-3.png',
        imageIdsZh: '' 
    };
    
    
    // takes the json 'data' as its 1st parameter
    // and the desired 'property' to be searched as the 2nd parameter
    // for loop iterates through the entire json
    // if the property parameter matches a 'key' name in json e.g. 'imageIds'
    // then the value for that property is returned
    function fetchProperty (data, property) {
        for(var key in data) {
            if(key === property) {
                return data[key];
            }   
        }
    }
    
    
    // if you wanted to return a bunch of data according to a particular key - value pair
    // you could do something like this...
    // assume 'array' contains a bunch of jsons 
    // newData will hold jsons containing your newly fetched data points
    function fetchNewData() {
       var newData = [];
       for(var i = 0; i < array.length; i++) {
    
          var value1 = fetchProperty(array[i], 'imageIds');
          var value2 = fetchProperty(array[i], 'imageIdsZh');
          var value3 = fetchProperty(array[i], 'imageIdsBlah');
    
          var tempJSON = {};
          tempJSON.imageIds = value1;
          tempJSON.imageIdsZh = value2;
          tempJSON.imageIdsBlah = value3;
    
          newData.push(tempJSON);
       }
       return newData;
    }    
    

    ** I hope this was helpful. If you have any further questions, feel free to reach out. Best of luck. **

提交回复
热议问题