最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

javascript - Get ids from array of objects - Stack Overflow

programmeradmin3浏览0评论

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"}];

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"}];
Share Improve this question edited Apr 16, 2019 at 10:35 jo_va 14k3 gold badges25 silver badges49 bronze badges asked Apr 16, 2019 at 7:24 minnu merin alexminnu merin alex 971 gold badge2 silver badges9 bronze badges 3
  • 1 what you actually want to do?? – Syed Kashif Commented Apr 16, 2019 at 7:27
  • Could you explain the relation between your Input and Output ? Are you filtering ? based on what criteria ? How do you transform your Input ? – jo_va Commented Apr 16, 2019 at 10:36
  • 1 id's should be unique, why are you keeping same id for every object ? – Code Maniac Commented Apr 16, 2019 at 10:39
Add a ment  | 

2 Answers 2

Reset to default 3

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
  };
})
发布评论

评论列表(0)

  1. 暂无评论