0

I am getting this response from an API:

{
  "statuses": {
    "status": [
      {
        "name": "Member", 
        "id": "1"
      }, 
      {
        "name": "Attender", 
        "id": "3"
      }, 
      {
        "name": "Child", 
        "id": "4"
      }
    ]
  }
}

But I need to somehow flatten the response to be this:

{
  "name": "Member", 
  "id": "1"
}, 
{
  "name": "Attender", 
  "id": "3"
}, 
{
  "name": "Child", 
  "id": "4"
}

How can I do that using Javascript?

3
  • 2
    isn't the status key has the same values in the array. Why don't you just do response.statuses.status where response is your variable name. Commented Jul 24, 2015 at 3:47
  • 1
    you just need to pull response.statuses.status? Commented Jul 24, 2015 at 3:47
  • 1
    Yes, you just need to retrieve by using response.statuses.status. Commented Jul 24, 2015 at 3:54

3 Answers 3

3

var response = {
  "statuses": {
    "status": [
      {
        "name": "Member", 
        "id": "1"
      }, 
      {
        "name": "Attender", 
        "id": "3"
      }, 
      {
        "name": "Child", 
        "id": "4"
      }
    ]
  }
}

var statusObj = response.statuses.status;

$('#result').text('First name is: ' + statusObj[0].name)
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>

<label id="result"/>

Sign up to request clarification or add additional context in comments.

Comments

2

You can do JSON.parse(str) and then you you just take the data from status[x]

If you really want to keep it as a string you can do var content = str.match(/\[(.*?)\]/);

Comments

0

In fact, you just need to retrieve by response.statuses.status from your Javascript object.

But , If you needed to convert json to javascript object,
please use JSON.parse(your json response) method using JSON.js.

Download the JSON.js from https://github.com/douglascrockford/JSON-js

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.