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 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 }
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];
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With