如何从对象数组中找到数组的所有ID-Javascript

时间:2019-09-30 07:02:11

标签: javascript

如何从对象数组中找到数组的所有ID。通过正常的for循环,我可以通过findAll等获得但使用ECMA新功能。如何获得?

let items = [
      {id: 28, name: "Action", isSelected: true},
      {id: 10770, name: "TV Movie", isSelected: false},
      {id: 53, name: "Thriller", isSelected: true},
      {id: 10752, name: "War", isSelected: false},
      {id: 37, name: "Western", isSelected: true}
    ]

在这里我想找到所有基于isSelected的id是true。

4 个答案:

答案 0 :(得分:1)

使用过滤器和地图

let items = [
      {id: 28, name: "Action", isSelected: true},
      {id: 10770, name: "TV Movie", isSelected: false},
      {id: 53, name: "Thriller", isSelected: true},
      {id: 10752, name: "War", isSelected: false},
      {id: 37, name: "Western", isSelected: true}
    ]
    console.log(items.filter(function(e){return e.isSelected}).map(function(e){
    return e.id
    }))

答案 1 :(得分:1)

尝试一下:

let items = [
  { id: 28, name: "Action", isSelected: true },
  { id: 10770, name: "TV Movie", isSelected: false },
  { id: 53, name: "Thriller", isSelected: true },
  { id: 10752, name: "War", isSelected: false },
  { id: 37, name: "Western", isSelected: true }
]
let res = items.filter(({ isSelected }) => isSelected).map(({id}) => id);
console.log(res);

答案 2 :(得分:1)

简单的地图功能即可完成工作

let items = [
      {id: 28, name: "Action", isSelected: true},
      {id: 10770, name: "TV Movie", isSelected: false},
      {id: 53, name: "Thriller", isSelected: true},
      {id: 10752, name: "War", isSelected: false},
      {id: 37, name: "Western", isSelected: true}
]

items.map(item => console.log(item.id))

答案 3 :(得分:1)

首先过滤数组以获取isSelectedtrue的对象,然后使用map()获取那些对象的id

let items = [
      {id: 28, name: "Action", isSelected: true},
      {id: 10770, name: "TV Movie", isSelected: false},
      {id: 53, name: "Thriller", isSelected: true},
      {id: 10752, name: "War", isSelected: false},
      {id: 37, name: "Western", isSelected: true}
];
let res = items.filter(({isSelected}) => isSelected).map(({id}) => id);
console.log(res);