gpt4 book ai didi

javascript - 如何检查数组中的属性

转载 作者:行者123 更新时间:2023-12-02 23:05:20 25 4
gpt4 key购买 nike

我正在调用服务电话,以获取一些数据。例如:

var response = [
{id: 1, name: 'text1'},
{id: 2, name: 'text2'}
];

这个数组代表了我能得到的最有可能的数据。在其他情况下,我可能会返回一个空数组,该数组仅包含这些对象之一(或者数组内的对象)。我想以某种方式循环遍历我的数组并检查每个 on=bject 的 id 以便为前端设置一个标志以显示其他数据。对于我上面提到的场景,如何正确检查数组中的 id?

最佳答案

使用Array.some()

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/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com