Home > Blockchain >  How do you check if value exist in object of object's array?
How do you check if value exist in object of object's array?

Time:03-30

I want to know which logic i should use to check every object's array of parent object contained in grand parent object

Hi guys i want to check if this value for example : "127.0.0.1" exists in this object (MyObject has like 2k objects in it)

{
  "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",
           ]
         }
      }
    ]
}

Btw does include() needs to match the whole string or for example if 127.0.0.1 is like this in my object 127.0.0.1/32, i can still retrieve it even if there is a ip range ?

CodePudding user response:

Your data is structured quite specifically, so you can write a custom method which you can call over and over again. It will check for a

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));

CodePudding user response:

Array.flatMap implementation

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);

If you want check if the partial ip addess is included in the list, you should make use of a regex implementation.

Sample Implementation

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);

  • Related