我想知道我應該使用哪種邏輯來檢查包含在祖父物件中的每個物件的父物件陣列
大家好,我想檢查這個值是否例如:“127.0.0.1”存在于這個物件中(MyObject 中有 2k 個物件)
{
"name" : MyObject
"value": [
{
"name" : "Object1",
"properties":{
"address" : [
"13.65.25.19/32",
"13.66.60.119/32",
]
}
},
{
"name" : "Object2",
"properties":{
"address" : [
"13.65.25.19/32",
"127.0.0.1",
]
}
}
]
}
順便說一句,include() 是否需要匹配整個字串,或者例如,如果 127.0.0.1 在我的物件 127.0.0.1/32 中是這樣的,即使有一個 IP 范圍,我仍然可以檢索它?
uj5u.com熱心網友回復:
您的資料結構非常具體,因此您可以撰寫一個可以反復呼叫的自定義方法。它會檢查一個
const obj = {
name: 'MyObject',
value: [
{
name: 'Object1',
properties: {
address: ['13.65.25.19/32', '13.66.60.119/32'],
},
},
{
name: 'Object2',
properties: {
address: ['13.65.25.19/32', '127.0.0.1'],
},
},
],
};
const address = '127.0.0.1';
const includesAddress = (address) => {
for (const val of obj.value) {
if (val.properties.address.some((a) => address === a)) return true;
}
return false;
};
console.log(includesAddress(address));
uj5u.com熱心網友回復:
Array.flatMap執行
const obj = {
name: 'MyObject',
value: [
{
name: 'Object1',
properties: {
address: ['13.65.25.19/32', '13.66.60.119/32'],
},
},
{
name: 'Object2',
properties: {
address: ['13.65.25.19/32', '127.0.0.1'],
},
},
],
};
const address = '127.0.0.1';
const output = obj.value.flatMap(item => item.properties.address).includes(address);
console.log(output);
如果要檢查串列中是否包含部分 ip 地址,則應使用正則運算式實作。
示例實作
const obj = {
name: 'MyObject',
value: [
{
name: 'Object1',
properties: {
address: ['13.65.25.19/32', '13.66.60.119/32'],
},
},
{
name: 'Object2',
properties: {
address: ['13.65.25.19/32', '127.0.0.1'],
},
},
],
};
const address = '13.65.25.19';
const regex = new RegExp(address, 'i')
const output = obj.value.flatMap(item => item.properties.address).filter(x => regex.test(x)).length > 0;
console.log(output);
轉載請註明出處,本文鏈接:https://www.uj5u.com/yidong/453649.html
標籤:javascript 数组 目的
下一篇:使用通用方法接收器實作介面
