我正在调用服务电话,以获取一些数据。例如:
var response = [
{id: 1, name: 'text1'},
{id: 2, name: 'text2'}
];
这个数组代表了我能得到的最有可能的数据。在其他情况下,我可能会返回一个空数组,该数组仅包含这些对象之一(或者数组内的对象)。 我想以某种方式循环遍历我的数组并检查每个 on=bject 的 id 以便为前端设置一个标志以显示其他数据。对于我上面提到的场景,如何正确检查数组中的 id?
最佳答案
var response = [{ id: 1, name: "text1" }, { id: 2, name: "text2" }];
var exists = (id, arr) => arr.some(e => e.id === id);
var id1Exists = exists(1, response);
var id2Exists = exists(2, response);
var id3Exists = exists(3, response);
console.log({ id1Exists, id2Exists, id3Exists });
关于javascript - 如何检查数组中的属性,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/57610922/