Json parse array

Asked

Viewed 701 times

2

I have the following answer

{
    "users":[
        {
            "id":1,
            "Name":"Rafael",
            "label":"teste"
        },
        {
            "id":2,
            "Name":"Carlos",
            "label":"teste"
        }
    ],
    "relations":[
        {
            "id":1
        },
        {
            "id":2
        }
    ]
}

And I want to armanezar in two arrays of objects

var usersArray;
var relationsArray;

I’ve tried so many ways and .map(JSON.parse) does not work on my page.

  • var usersArray = json.users;
var relationsArray = json.relations;

2 answers

4

You can store this response in a variable and separate the two arrays:

var arrJson = {
        "users":[
            {
                "id":1,
                "Name":"Rafael",
                "label":"teste"
            },
            {
                "id":2,
                "Name":"Carlos",
                "label":"teste"
            }
        ],
        "relations":[
            {
                "id":1
            },
            {
                "id":2
            }
        ]
    }

var users = arrJson.users;
var relations = arrJson.relations;

console.log(users)
console.log(relations)

That way I managed, without having to call any conversion method, to separate the two Arrays

  • You know you can create a snnipet here on the site same?

  • I’ve seen some answers, but I don’t quite know how you do it, so I usually create a Fiddle

  • Has a button Trecho JavaScript/HTML/CSS in the top bar of the field to write reply. Or just click Ctrl + M

  • Man, thank you so much, much better kkk I’ll never use Jsfiddle again

2

Simply assign the respective object values to the variables:

const resposta = {
    "users":[
        {
            "id":1,
            "Name":"Rafael",
            "label":"teste"
        },
        {
            "id":2,
            "Name":"Carlos",
            "label":"teste"
        }
    ],
    "relations":[
        {
            "id":1
        },
        {
            "id":2
        }
    ]
};

var usersArray = resposta["users"];
var relationsArray = resposta["relations"];

console.log(usersArray);
console.log(relationsArray);

The exit of console.log(usersArray) will be:

[
  {
    "id": 1,
    "Name": "Rafael",
    "label": "teste"
  },
  {
    "id": 2,
    "Name": "Carlos",
    "label": "teste"
  }
]

And of console.log(relationsArray) will be:

[
  {
    "id": 1
  },
  {
    "id": 2
  }
]

Browser other questions tagged

You are not signed in. Login or sign up in order to post.