Get a slice of a Javascript Associative Array?

12,209

Solution 1

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];
}

Solution 2

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;
}

Solution 3

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 }
Share:
12,209
David Savage
Author by

David Savage

Updated on July 20, 2022

Comments

  • David Savage
    David Savage almost 2 years

    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!

  • Ivo Wetzel
    Ivo Wetzel over 13 years
    Missing hasOwnProperty... explodes in 3...2...1... ;)
  • David Savage
    David Savage over 13 years
    Hmm, so basically I just have to loop through the object properties? Since my object has all the properties I need in the sliced object together, couldn't I just increment an int while looping and only get the numbers I need? i.e. if (i > 0 && i < 11)?
  • Raynos
    Raynos over 13 years
    @IvoWetzel If there's code on the page that adds enumerable properties on the Object prototype then it's their own damn fault!
  • Ivo Wetzel
    Ivo Wetzel over 13 years
    @Raynos What about poor people using Prototype? :P
  • g.d.d.c
    g.d.d.c over 13 years
    @David Savage - Essentially, yes, you loop over the ones you know you need and add them to your 'slice'. You can certainly loop while incrementing an int, but depending on the size of your original object you may end up with performance penalties (if you have 1000 items to check and need 10 you're performing 990 extra checks). If they're conveniently arranged you could break the loop early to avoid some of that penalty.
  • user113716
    user113716 over 13 years
    @David, g.d.d.c: Don't do for/in over an Array. It is a useful practice to prototype Array with additional methods when needed, and for/in will pick those up. Better to use a traditional for loop.
  • zykadelic
    zykadelic almost 10 years
    There's also the opposite (except) available. It works directly on the object though, instead of returning a new copy.
  • Daniel Loureiro
    Daniel Loureiro about 8 years
    Thanks zykadelic, this has helped me a lot.
  • zykadelic
    zykadelic about 8 years
    @DanielLoureiro I'm glad :)