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

前端 未结 5 1702
一整个雨季
一整个雨季 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:23

    Some functional style awesomeness:

    var data = {
        title: 'fsdfsd',
        titleZh: 'fsdfsd',
        body: 'fsdf',
        bodyZh: 'sdfsdf',
        imageIds: '/uploads/tmp/image-3.png',
        imageIdsZh: '' 
    };
    
    var z = Object.keys(data).filter(function(k) {
        return k.indexOf('imageIds') == 0;
    }).reduce(function(newData, k) {
        newData[k] = data[k];
        return newData;
    }, {});
    
    console.log(z);
    

    Demo: http://jsfiddle.net/ngX4m/

    Some minor explanation:

    1. We use Array.prototype.filter() function to filter out the keys that start with `imageIds2
    2. We use Array.prototype.reduce() to convert an array of filtered keys into an object of key-value pairs. For that we use the initial value of {} (an empty object), fill it and return from every execution step.

    UPD:

    A fair update from @GitaarLAB:

    Object.keys is ES5, but returns an objects own properties (so no need for obj.hasOwnProperty(key))

提交回复
热议问题