Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

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!

like image 418
David Savage Avatar asked Dec 09 '10 17:12

David Savage


3 Answers

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;
}
like image 39
pleerock Avatar answered Nov 15 '22 15:11

pleerock


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 }
like image 22
zykadelic Avatar answered Nov 15 '22 16:11

zykadelic


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];
}
like image 130
g.d.d.c Avatar answered Nov 15 '22 14:11

g.d.d.c