0

I've a REST API which contains data in JSON format. I'm storing it in an array of objects. But I want to append a NEW EMPTY array to each object. I'm not able to do it. Here is how my REST API looks like. I marked the new array which I want to add for each object in the comments.

       content = [
          {
            text: 'abc',
            options: [
                {
                  Id: 1,
                  Text: 'aaa'
                },
                {
                  Id: 2,
                  Text: 'bbb'
                },
                {
                  Id: 3,
                  Text: 'ccc'
                }],
// ARRAY[]

    },
          {
            text: 'def',
            options: [
                {
                  Id: 21,
                  Text: 'qwerty'
                },
                {
                  Id: 22,
                  Text: 'zxcv'
                },
                {
                  Id: 23,
                  Text: 'asdf'
                }],
    // ARRAY[]
          }
      }]

here is what I've tried.

public newarr:Array<any>;
this.httpservice.post('RESTUrl').subscribe(resp=>{
     this.contents = resp.data;
     this.contents.forEach((x:any)=>{
       x.push(this.newarr);
     });
     console.log("contents",this.contents);
      });

2 Answers 2

1

All you nee to do is to Add is simply using dot notation.

this.httpservice.post('RESTUrl').subscribe(resp=>{
   this.contents = resp.data;
   this.contents.forEach((x:any)=>{
     x.<value_name> = this.newarr;
   });
   console.log("contents",this.contents);
});

This way it will append your variable to the Array.

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

6 Comments

Thanks so much. It works.But is it the same for arrays as well ?
Yes you can add arrays as well
Is it the same way or do I need to write it like this : x.arr[]=this.newarr ?
you don't need to add []. It will automatically take it. As all you are doing is appending Array to JSON array variable not Typescript variable.
Nope.. It didn't work for me when I put it like this : var newarr:Array<any>=[]; this.contents.forEach(x => { x.arr = newarr; }); But this worked : this.contents.forEach(x => { x.arr = new Array(x.choices.length); });
|
1

It looks like you're trying to push an array onto an object, it should be x.NewArray = this.newarr or something.

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.