在Javascript中查找基于匹配的键值



我正在尝试返回uid,其中urn键具有此匹配。

"urns"("whatsapp: 27820111111"),

应该返回什么d7b9f88c-b359-4d69-926d- 536c0d28920e0,因为它有那个电话号码匹配。如何用编程的方式来完成呢?

这是两本字典。

{
"next": "https://random.com=",
"previous": null,
"results": [ 
{
"uuid": "g2ws8dh5-b359-4d69-926d-536c0d2892e0",
"name": "James",
"language": "eng",
"urns": [
"whatsapp:27333333333"
],
"groups": [
{
"uuid": "57fs8430-3c78-42b7-876c-c385e36c1dba",
"name": "Postbirth WhatsApp"
}
],
"fields": {
"whatsapp_consent": null,
"webhook_failure_count": null,
},
"blocked": false,
"stopped": false,
"created_on": "2020-12-01T07:50:58.736502Z",
"modified_on": "2020-12-01T08:36:34.980359Z"
},
{
"uuid": "d7b9f88c-b359-4d69-926d-536c0d2892e0",
"name": "Jane",
"language": "eng",
"urns": [
"whatsapp:27820111111"
],
"groups": [
{
"uuid": "e35f2e39-3c78-42b7-876c-c385e36c1dba",
"name": "Prebirth WhatsApp"
}
],
"fields": {
"whatsapp_consent": null,
"webhook_failure_count": null,
},
"blocked": false,
"stopped": false,
"created_on": "2020-12-01T07:50:58.736502Z",
"modified_on": "2020-12-01T08:36:34.980359Z"
}
]

}

我能够循环并找到骨灰盒,但我不确定如何退后一步获得液体。

将结果数组和urn字符串传递给此函数。如果找到它将返回uid,否则返回null。

function getIdFromUrn(results, urn) {
for (let i = 0; i < results.length; i++) {
const result = results[i];
if (result.urns.includes(urn)) {
return result.uuid; // urn found
}
}
return null; // not found
}
console.log(getIdFromUrn(results, 'whatsapp:27820111111'));

当你可以使用find(...)来匹配一个值时,你不需要循环。

参见下面的演示

var data = [{
"uuid": "g2ws8dh5-b359-4d69-926d-536c0d2892e0",
"name": "James",
"language": "eng",
"urns": [
"whatsapp:27333333333"
],
"groups": [{
"uuid": "57fs8430-3c78-42b7-876c-c385e36c1dba",
"name": "Postbirth WhatsApp"
}],
"fields": {
"whatsapp_consent": null,
"webhook_failure_count": null,
},
"blocked": false,
"stopped": false,
"created_on": "2020-12-01T07:50:58.736502Z",
"modified_on": "2020-12-01T08:36:34.980359Z"
},
{
"uuid": "d7b9f88c-b359-4d69-926d-536c0d2892e0",
"name": "Jane",
"language": "eng",
"urns": [
"whatsapp:27820111111"
],
"groups": [{
"uuid": "e35f2e39-3c78-42b7-876c-c385e36c1dba",
"name": "Prebirth WhatsApp"
}],
"fields": {
"whatsapp_consent": null,
"webhook_failure_count": null,
},
"blocked": false,
"stopped": false,
"created_on": "2020-12-01T07:50:58.736502Z",
"modified_on": "2020-12-01T08:36:34.980359Z"
}
];
const lookingFor = "whatsapp:27820111111";
const foundIt = data.find(el => {
return (el.urns.indexOf(lookingFor) !== -1);
});
console.log(foundIt.uuid);

最新更新