0

I am getting a response from an API, and this is the response when I viewed it using console.log(myArray).

I need to write the code in TypeScript Angular 6.

Output:Array(2)

 0:{ q1: 2
       q2:. 1
        __proto__: Object
     }
 1:{ q1: 2
       q2:. 1
      __proto__: Object
    }
 ___proto__: Array(0)
__proto__:object

Now I need to get the values of q1 and q2 in array. I tried but I am unable to do it.

How can I do that?

2
  • 1
    do you want it in HTML or inside component only Commented Feb 11, 2019 at 16:35
  • 1
    Can you provide the code you've tried so far? Commented Feb 11, 2019 at 16:35

2 Answers 2

1

So, your Array has 2 elements in it.

1st is {q1: 2, q2:..}

the 2nd is {q1: 2, q2:..} also.

It looks like this: [{q1: 2, q2: ..}, {q1: 2, q2: ..}]

So you need the values of q1 and q2 out of array? Well, you have two copies of q1/q2 in your two separate objects. It's unclear whether they are the same.

If you just need the q1/q2 from the first object in your array, you can do the following:

let arr = [{q1: 2, q2: 3}, {q1: 2, q2: 3}]
arr[0].q1 // this is q1
arr[0].q2 // this is q2

If the q1/q2 values in each object are different, and you need all values of q1/q2, then you will need to loop through your array and get q1/q2 one by one. Like so:

let arr = [{q1: 2, q2: 3}, {q1: 2, q2: 3}]
arr.forEach(obj => console.log(obj.q1, obj.q2));
Sign up to request clarification or add additional context in comments.

Comments

0

Here is your solution:

result = [];
getResult(myArray) {
  for(let i = 0;i < myArray.length;i++) {
    this.result.push(myArray[i]['q1']);
    this.result.push(myArray[i]['q2']);
   }
console.log(this.result);
return this.result;
}

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.