开发者

Get a slice of a Javascript Associative Array? [duplicate]

This question already has answers here: How to get a subset of a javascript object's properties (36 answers) Closed 6 years ago.

I have an associative array object in Javascript that I need only part of. With a regular array, I would just use slice to get the part I开发者_如何转开发 need, but obviously this won't work on an associative array. Is there any built in Javascript functions that I could use to return only part of this object? If not, what would be considered best practices for doing so? Thanks!


There's not going to be a good way to 'slice' the Object, no, but you could do this if you really had to:

var myFields = ['field1', 'field2', 'field3'];

var mySlice = {};

for (var i in myFields) {
  var field = myFields[i];

  mySlice[field] = myOriginal[field];
}


There is small function I use:

/**
 * Slices the object. Note that returns a new spliced object,
 * e.g. do not modifies original object. Also note that that sliced elements
 * are sorted alphabetically by object property name.
 */
function slice(obj, start, end) {

    var sliced = {};
    var i = 0;
    for (var k in obj) {
        if (i >= start && i < end)
            sliced[k] = obj[k];

        i++;
    }

    return sliced;
}


I've created this gist that does exactly this. It returns a new object with only the arguments provided, and leaves the old object intact.

if(!Object.prototype.slice){
    Object.prototype.slice = function(){
        var returnObj = {};
        for(var i = 0, j = arguments.length; i < j; i++){
            if(this.hasOwnProperty(arguments[i])){
                returnObj[arguments[i]] = this[arguments[i]];
            }
        }
        return returnObj;
    }
}

Usage:

var obj = { foo: 1, bar: 2 };

obj.slice('foo'); // => { foo: 1 }
obj.slice('bar'); // => { bar: 2 }
obj;              // => { foo: 1, bar: 2 }
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜