1

I have a JSON response , Below is my response.

{
    "data": [
        {
            "2": [
                {
                    "name": "Test1",
                    "Address": "Test2"
                },

            ]
        },
         {
            "5": [
                {
                    "name": "Test3",
                    "Address": "Test4"
                },

            ]
        },


    ]
}

I am able to access till data from the response.Here "2" and "5" are date.If one date is present in this json response then for that response i have to get name and address But I have to show list of data.

<div *ngFor = "let data of result">
<span>{{data.name}}</span>
<span>{{data.Address}}</span>
</div>

In ts file,

 let result = response.data;

I want to access name and address from this.Can anyone please help me how to do this.

1 Answer 1

3

You can use Object.key, map and concat function to flat your data like this

let obj = this.result;
this.result = Object.keys(obj).map(function (key) {   
  let objkey = obj[key];
  let first = Object.keys(objkey)[0]
  return obj[key][first];
});

this.result = [].concat.apply([], this.result);

Demo at https://stackblitz.com/edit/angular-flat-array-property

Updated:

I update demo with filter to apply your filter by date.

    let obj = this.result;
    var filter = '5';
    this.result = Object.keys(obj).map(function (key) {
      let objkey = obj[key];
      let first = Object.keys(objkey)[0]
      if(filter == first){
         return obj[key][first];
      }else{
        return null;
      }

    });

    this.result = [].concat.apply([], this.result.filter(c=>c != null));
Sign up to request clarification or add additional context in comments.

2 Comments

My requirement is like if date is 2nd, then only 2nd date data should display in list. If date is 5th, then 5th date data should display in list.basically i need to filter this based on date.Can you help me how to do this. @Hien Nguyen
Yes this is working . This is what exactly i was looking for. Thanks a lot :) . Really this saved my day. @Hien Nguyen

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.