Joey Hipolito
Joey Hipolito

Reputation: 3166

removing the key from a key value pair of objects in javascript

Let's say I have this Array of objects:

[300: {a:"some", b:"value"}, 301: {a: "another", b: "val"} ...]

I have that kind of object and I am iterating using recursive function, and there's no way I will change my counter to start at 300, I always start at 0.

I am thinking of a solution, to remove the keys from the agrray so that I will have an array like so:

[{a:"some", b:"value"}, {a: "another", b: "val"} ...]

How do I do that in javascript? Also, if there is another way that would be much faster than creatng a function that will remove keys, it will be much better.

Upvotes: 0

Views: 100

Answers (3)

Mehran Hatami
Mehran Hatami

Reputation: 12961

There is a point here that should be clarified. When you have a Array object which its values starts from 300 as its indexes, it means you have 300 indexes with undefined values, but if it is just an Array-like object it could be totally different.

Let's say this is not an Array-like and is an actual Array, so you have to filter it so that all the undefined values get removed from your array, so your array should be like:

var arr = [/*0*/undefined, ..,/*299*/undefined, /*300*/{a:"some", b:"value"}, /*301*/ {a: "another", b: "val"} ...]
var result = arr.filter(function(value,index){
    return (value !== undefined);
});

but what you have mentioned in your question, is more likely a javascript object, so to do what you want you can do:

var myObj = {300: {a:"some", b:"value"}, 301: {a: "another", b: "val"} };
var result = {};
for(var key in obj){
    if(obj.hasOwnProperty(key)){
        result.push(obj[key]);
    }
}

in this for loop hasOwnProperty function helps you make sure if it is one of the actual object values, and not other possible keys from the object's prototype chain.

Upvotes: 1

jonasnas
jonasnas

Reputation: 3570

If you meant that the initial structure of array is this:

var data = [{300: {a:"some", b:"value"}}, {301: {a: "another", b: "val"}}];

then this should work (result array):

var result = [];
var data = [{300: {a:"some", b:"value"}}, {301: {a: "another", b: "val"}}];
for(var i =0; i < data.length; i++){
    for(var key in data[i]) {
        if(data[i].hasOwnProperty(key)) {
            result.push(data[i][key]);
            break;
        }
    }
}

Upvotes: 1

Andy
Andy

Reputation: 63524

This will give you a syntax error (SyntaxError: missing ] after element list):

var data = [300: {a:"some", b:"value"}, 301: {a: "another", b: "val"}];

You mean this:

var data = {300: {a:"some", b:"value"}, 301: {a: "another", b: "val"}};

And to convert that into an array, loop over the object and push each value into a new array:

var arr = [];
for (var k in data) {
  arr.push(data[k]);
}

Fiddle

Upvotes: 1

Related Questions