-1

I have this JSON array:

{
  "data": [
    {
      "id": 6,
      "pnome": "dasda",
      "unome": "dad",
      "avatar": 1,
      "email": "d",
      "pass": "password",
      "ponto": 0
    },
    {
      "id": 3,
      "pnome": "Enguias",
      "unome": "Enguias outra vez",
      "avatar": 10,
      "email": "enguias@enguias.enguias",
      "pass": "enguias",
      "ponto": 0
    },
    {
      "id": 2,
      "pnome": "André",
      "unome": "Marques",
      "avatar": 1,
      "email": "aglmarque@gmail.com",
      "pass": "yet1",
      "ponto": 0
    }
  ]
}

And i'm putting it into an array with axios, like this:

    axios.get(my_url_api)
    .then((res)=>{
        const txt = JSON.stringify(res.data.data);
        const users = JSON.parse(txt)
    })

Which makes the users array have all the info in the JSON file. How can I make it so that I only pass specific attributes like email and pass? It would look like this:

{
  "data": [
    {
      "email": "d",
      "pass": "password"
    },
    {
      "email": "enguias@enguias.enguias",
      "pass": "enguias"
    },
    {
      "email": "aglmarque@gmail.com",
      "pass": "yet1"
    }
  ]
}
ray
  • 26,557
  • 5
  • 28
  • 27
Enguias
  • 73
  • 2
  • 7
  • 3
    Why are you stringifying data that came directly from JSON? and then immediately parsing it again? – evolutionxbox Jun 14 '21 at 23:52
  • Yes, you can just do `const users = res.data.data`. Also, it's not a JSON array. It's JSON (text), which is parsed into an array by axios. Understanding this distinction will make it easier to realize when you actually need JSON.stringify and JSON.parse (you very often don't). All this if completely irrelevant anyway though; this is about removing properties from the objects in an array. –  Jun 15 '21 at 00:19
  • 2
    Duplicate: [Remove property for all objects in array](https://stackoverflow.com/questions/18133635/remove-property-for-all-objects-in-array) –  Jun 15 '21 at 00:20

1 Answers1

2

You can use Array.map() function to remove the unnecessary fields like following example:

let res = {
"data": [
{
"id": 6,
"pnome": "dasda",
"unome": "dad",
"avatar": 1,
"email": "d",
"pass": "password",
"ponto": 0
},
{
"id": 3,
"pnome": "Enguias",
"unome": "Enguias outra vez",
"avatar": 10,
"email": "enguias@enguias.enguias",
"pass": "enguias",
"ponto": 0
},
{
"id": 2,
"pnome": "André",
"unome": "Marques",
"avatar": 1,
"email": "aglmarque@gmail.com",
"pass": "yet1",
"ponto": 0
}
]
}

res.data = res.data.map(item => {
  return {
  email: item.email,
  pass: item.pass
  };
});

console.log(res);
Robin Mollah
  • 116
  • 2
  • 8
  • 1
    One-liner with destructuring: `res.data = res.data.map(({ email, pass }) => ({ email, pass })` – ray Jun 15 '21 at 00:01
  • 2
    If you immediately know the answer, it's very likely a duplicate. Please check first. –  Jun 15 '21 at 00:21