29

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.

3
  • 3
    Try this stackoverflow.com/questions/19590865/… Commented Dec 17, 2016 at 10:20
  • 5
    Also you start with an array. myObj.map(thing => thing.id) would suffice. Commented Dec 17, 2016 at 10:22
  • Yes map will do the things thanks Jonathan and jonrshare Commented Dec 17, 2016 at 10:24

2 Answers 2

86

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);

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

1 Comment

We can make type script like too "myObj.map(p=>p.id)"
-9
<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>

1 Comment

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.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.