0

In Angular, I am getting multi dimension array as a response from backend. I want to capture only one array data into my new array with only few values from it (id and fname). I tried multiple ways but things did not work for me. Below are the details.

Multi dimension array json response from backend.

{
   "data":[
      {
         "SRno":{
            "label":"newtest",
            "label1":"10 VINS"
         },
         "attachment":{
            "value":null,
            "label":null
         },
         "username":{
            "id":2,
            "fname":"test1",
            "lname":"test11"
         }        
      },
      {
         "SRno":{
            "label":"newtest1",
            "label":"10 VINS"
         },
          "attachment":{
            "value":null,
            "label":null
         },
         "username":{
            "id":3,
            "name":"test2",
            "lname":"test22"
           }
      },
      {
         "SRno":{
            "label":"newtest2",
            "label":"10 VINS"
         },
          "attachment":{
            "value":null,
            "label":null
         },
         "username":{
            "id":4,
            "name":"test3",
            "lname":"test33"
         }
      },
      {
         "SRno":{
            "label":"newtest3",
            "label":"10 VINS"
         },
          "attachment":{
            "value":null,,
            "label":null
         },
         "username":{
            "id":5,
            "name":"test4",
            "lname":"test44"
         }
      }      
   ],
   "result":null
}

Expected Output:

"Newarray":[
         {
            "id":2,
            "fname":"test1"
         },
         {    
            "id":3,
            "name":"test2"
         },
         {
            "id":4,
            "name":"test3"
         },
         {
            "id":5,
            "name":"test4"
         }
        ]
James Z
  • 12,209
  • 10
  • 24
  • 44
Bhushan Khaladkar
  • 420
  • 1
  • 7
  • 20

2 Answers2

1
response['data'].map(({ username: { id, fname }}) => ({ id, fname }));

If you want to take name instead of fname when fname is missing, you can do this:

response['data'].map(({ username: { id, fname, name }}) => ({ id, fname: fname ?? name }));

Take a look at this playground.

carlosV2
  • 1,167
  • 6
  • 15
0

Using your data as an example, and assigning the variable from the backend to payload you could do it this way

const usernameObj = payload.data.map(obj => ({ id: obj.username.id, fname: obj.username.fname ?? obj.username.name }))
Jorge Guerreiro
  • 682
  • 6
  • 22