简体   繁体   中英

Get ids from array of objects

I am new to Typescript. I want to select ids from observable I have an array as below. Please help me to get the expected output.

const Input=[{
  "id": 1,
  "text": "My Choice 1"
}, {
  "id": 2,
  "text": "My Choice 2"
}, {
  "id": 3,
  "text": "My Choice 3"
}, {
  "id": 4,
  "text": "My Choice 4"
}, {
  "id": 5,
  "text": "My Choice 5"
}];

Expected Result :

let selectedIds = [
      {id: "Choice", name: "2"},
      {id: "Choice", name: "3"},
      {id: "Choice", name: "5"}];

Use array.map to transform the objects

 const Input=[{ "id": 1, "text": "My Choice 1" }, { "id": 2, "text": "My Choice 2" }, { "id": 3, "text": "My Choice 3" }, { "id": 4, "text": "My Choice 4" }, { "id": 5, "text": "My Choice 5" }]; let Result = Input.map(choice => ({ id: "choice", name: choice.id })); console.log(Result);

let selectedIds = Input.map(item => 
{
  return {
    id: item.text,
    name: item.id
  };
})

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM