25

I am new to Typescript. I want to select ids from observable

This is my observable

let myObj = [{
  "id": 1,
  "text": "Mary"
}, {
  "id": 2,
  "text": "Nancy"
}, {
  "id": 3,
  "text": "Paul"
}, {
  "id": 4,
  "text": "Cheryl"
}, {
  "id": 5,
  "text": "Frances"
}]

Expected Result :

let selectedIds = [1,2,3,4,5];

Can I do this without creating an array and pushing the ids in a for loop.

jonrsharpe
  • 115,751
  • 26
  • 228
  • 437
Sathya V
  • 589
  • 3
  • 7
  • 15

2 Answers2

76

Use Array#map to map one array to another:

const myObj = [{"id":1,"text":"Mary"},{"id":2,"text":"Nancy"},{"id":3,"text":"Paul"},{"id":4,"text":"Cheryl"},{"id":5,"text":"Frances"}];

const selectedIds = myObj.map(({ id }) => id);

console.log(selectedIds);
Ori Drori
  • 183,571
  • 29
  • 224
  • 209
-8
<script>
      ..........Your Ajax / JSON  Request Sending Code

      function success(response)
      {
            var arr = JSON.parse(response);

            var selectedIds  = new Array();

            for(var i=0;i < arr.length ; i++)
            {
                  selectedIds["[" + arr[i].id + "]"] ; 
            }
            document.write(selectedIds);
      }

</script>
Martijn Pieters
  • 1,048,767
  • 296
  • 4,058
  • 3,343
  • 1
    Try and provide an explanation along with the code snippet. It helps us understand your reasoning behind including the snippet. Additionally, the OP is specifically asking for a method of achieving this without looping through each item in the Array. – rootr Dec 14 '19 at 05:43