Christian Hill Christian Hill - 1 year ago 36
Javascript Question

How can I assign a key to an array of values to pass to an API?

Im using Angular with pure JS. I have an array like this:

arr = [1, 2, 5, 32];

But I need to POST this to an API in JSON. I'm trying to achieve this:

{'reportIDs': [1, 2, 5, 32]}

Is there an easy way to do this in Angular?

Answer Source

Wherever it is that you need this value, you can create that object almost exactly as in your question:

var obj = {'reportIDs': arr};

You don't need the ', but they don't do any harm.

But if you really need to send JSON, your example isn't JSON. In JSON, property names must be in double quotes. The simplest way to create valid JSON is to use JSON.stringify:

var json = JSON.stringify({reportIDs:arr});

If you're sending that somewhere, you'd use that value as the data in a $http call.

You might want to use angular.toJson instead of using JSON.stringify directly, as it skips some internal Angular prooperties.