Milos Milos - 17 days ago 7
JSON Question

How to parse json arrays into array rather than object

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.

Answer

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.

Comments