检查 jquery 中的对象中是否存在键

check if key exists in object in jquery

我开发了下面的代码,

var list = [];
// read data from api

$.each(data.samples, function(k, v) {
  if (!list.hasOwnProperty(v.key) 
    list.push({
      'key': v.key,
      'title': v.title.
      'sent': false
    }); 

console.log(list);

已更新(示例数据来自 API)

var obj ={
    "expand": "schema,names",
    "startAt": 0,
    "maxResults": 50,
    "total": 4,
    "samples": [
        {
            "key": "s-111",
            "title": {
                "summary": "title 1"
            }
        },
        {
            "key": "s-112",
            "title": {
                "summary": "title 2"
            }
        },
        {
            "key": "s-113",
            "title": {
                "summary": "title 3"
            }
        },
        {
            "key": "s-114",
            "title": {
                "summary": "title 3"
            }
        }
    ]
}

还有一些我不需要的必要的嵌套键值。 但是我只需要检查新密钥是否不存在将新密钥添加到我的列表中 API 每 2 分钟更新一次

一个问题是您正在检查对象的 属性 而不是对象的值,其中 v.key 未设置为推送到 [=13 的任何对象的 属性 =]数组。

您可以使用 .some() 迭代数组中的对象,通过返回 o.key === v.key 来检查数组中的任何对象是否具有 v.key 值,因为 v.key 设置为 "key" 属性 个对象被推送到数组。

var obj = {
  "expand": "schema,names",
  "startAt": 0,
  "maxResults": 50,
  "total": 4,
  "samples": [{
      "key": "s-111",
      "title": {
        "summary": "title 1"
      }
    },
    {
      "key": "s-112",
      "title": {
        "summary": "title 2"
      }
    },
    {
      "key": "s-113",
      "title": {
        "summary": "title 3"
      }
    },
    {
      "key": "s-114",
      "title": {
        "summary": "title 3"
      }
    },
    // duplicate entry to exclude
    {
      "key": "s-114",
      "title": {
        "summary": "title 3"
      }
    }
  ]
}

var list = [];
// read data from api

$.each(obj.samples, function(k, v) {
  if (!list.some(function(o) {
      return o.key === v.key
    }))
    list.push({
      "key": v.key,
      "title": v.title,
      "sent": false
    });
});

console.log(list);
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>

我不完全确定你在问什么,但据我了解,如果来自 data.samples 的键不存在,你想要做的是将对象添加到你的列表中在列表中?

在上面的例子中,你想要做的是这样的:

var list = [];
// read data from API

// Note Key, Value change
$.each(data.samples, function(key, value) {
    if (!list.includes(key)) {
        list.push({
            'key': v.key,
            title: v.title,
            'sent': false
        }); 
    }
}
console.log(list);

因为我现在没有测试这个的环境,所以我不能告诉你这是否适合你的目的。

但是,如果您尝试根据不在列表中的 添加,您将需要使用 key 参数,(不是参数的v.key值)根据JQuery Docs

虽然您可以使用 hasOwnProperty(...) 方法,但我建议您使用更特定于数组的 includes(...) 方法。可以找到文档 here.

同样,您可能需要进行一些额外的故障排除和哄骗才能使其适用于您的特定应用程序。

祝你好运 && 希望对你有所帮助!