如何在JS数组中搜索不同的元素?

时间:2017-12-04 01:34:49

标签: javascript arrays search

我有一个阵列。

var arr = [{"id": 1}, {"id": 2}, {"id": 1}];

我想在arr中搜索不同的元素。

arr[1]。 (== {"id":2}

如何搜索?

4 个答案:

答案 0 :(得分:1)

简单地

arr.find(e => e.id == 2);

答案 1 :(得分:0)

您还可以使用filter

var arr = [{"id": 1}, {"id": 2}, {"id": 1}];
console.log(arr.filter(obj => obj.id == 2));

答案 2 :(得分:0)

我认为这有区别:

const arr = [{"id": 1}, {"id": 2}, {"id": 1}]

const result1 = arr.find(e => e.id === 2)
const result2 = arr.filter(e => e.id === 2)
const result3 = arr.map(e => e.id).filter(id => id === 2)

console.log(result1, result2, result3)

答案 3 :(得分:-1)

你可以循环你的数组

@RequestMapping(value = "/insert",method = RequestMethod.POST)
    public @ResponseBody void createType(@ModelAttribute Type type) {
         if(Objects.equals(type.getDescription(), "")) {
             throw new NullPointerException("The description should not be empty.");
         }
         typeService.createType(type);
    }

   @RequestMapping(value = "/insert",method = RequestMethod.GET)
    public String createTypeForm(Model model) {
        model.addAttribute("insertType", new Type());
        return "insertType";
    }

请记住在循环时使用“of”而不是“in”。