Reputation: 1071
I have following foobar variable which is string(I get it like so by querying a webserver with $http.post):
var foobar = "[{param1: 'value1'}, {param2: 'value2'}]";
How do I make an array out of that? If I use JSON.parse, it will provide me with an object(tried typeof foobar
). But, if I then use delete param1
, it will then make it [null, {param2: 'value2'}]. What I want to do, basically is to remove first or second item. Also, value may be different, but keys will always stay the same, ie. they'll be numbers.
Upvotes: 1
Views: 83
Reputation: 7338
What's probably confusing you the most is typeof
.
In the case of arrays, typeof
will say it is an object (as you can read from MDN here). If you want to test to see if a variable is an array, you could use: foobar.isArray()
Upvotes: 0
Reputation: 24965
Seems like you're wanting to parse your array into a single object, from your delete statement. If so...
var foobar = '[{"param1":"value1"},{"param2":"value2"}]';
var json = JSON.parse(foobar);
json = json.reduce(function(previousValue, currentValue){
Object.keys(currentValue).forEach(function(key){
previousValue[key] = currentValue[key];
});
return previousValue;
}, {});
console.log(json);
I could be wrong though.
Upvotes: 2
Reputation: 352
As the others say, what you are providing is already an array.
var foobar = [{param1: 'value1'}, {param2: 'value2'}];
//You can see this because of the []
//You can delete the index of an array by using the splice method
foobar.splice(1,1);
//First param is the index, the second is the number of items to erase
Upvotes: 0
Reputation: 53958
This
var foobar = [{param1: 'value1'}, {param2: 'value2'}];
is an array.
var foobar = [{param1: 'value1'}, {param2: 'value2'}];
console.log(foobar instanceof Array)
If you want to remove the first item you can just use the shift
method:
var foobar = [{param1: 'value1'}, {param2: 'value2'}];
foobar.shift();
console.log(foobar)
While if you want to remove the second item you can use the pop
method:
var foobar = [{param1: 'value1'}, {param2: 'value2'}];
foobar.pop();
console.log(foobar)
Upvotes: 0
Reputation: 18753
This is already an array var foobar = [{param1: 'value1'}, {param2: 'value2'}];
.
var foobar = [{param1: 'value1'}, {param2: 'value2'}];
// this is an array
console.log(foobar);
// this is an object in an array
console.log(foobar[0]);
Upvotes: 0