【问题标题】:Typescript Select Ids from object [duplicate]打字稿从对象中选择ID [重复]
【发布时间】:2017-05-03 00:38:12
【问题描述】:

我是 Typescript 的新手。我想从 observable 中选择 ids

这是我观察到的

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

预期结果:

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

我可以在不创建数组并在 for 循环中推送 id 的情况下执行此操作吗?

【问题讨论】:

标签: arrays angular typescript rxjs rxjs5


【解决方案1】:
<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>

【讨论】:

  • 尝试提供解释以及代码 sn-p。它可以帮助我们理解您背后的推理,包括 sn-p。此外,OP 特别要求一种方法来实现这一点,而无需遍历 Array 中的每个项目。
【解决方案2】:

使用Array#map 将一个数组映射到另一个数组:

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

【讨论】:

  • 我们也可以制作像“myObj.map(p=>p.id)”这样的类型脚本
猜你喜欢
  • 2018-05-26
  • 1970-01-01
  • 2021-09-06
  • 2017-09-16
  • 2021-04-23
  • 1970-01-01
  • 1970-01-01
  • 2021-06-27
  • 2018-01-26
相关资源
最近更新 更多