Home > database >  How to check if a value of my array exists inside another object?
How to check if a value of my array exists inside another object?

Time:07-20

I have an array that I receive oid and name data and I need to compare if my oid value exists within an object.

This is my array:

const data  = [
    {
        "oid": "nbfwm6zz3d3s00",
        "name": "",
    },
    {
        "oid": "g74rvmr3cxpc0",
        "name": "",
    }
] 

This is my Object:

const myObj = {
  nbfwm6zd3s00: 'test value 1',
  g74rvmrcxpc0: 'test value 2'
)

How could I check if the oid value inside my data array exists in "myObj"?

CodePudding user response:

You can use Object.keys(obj) to run through all the keys then loop through your data. I changed a key so there was a matching key in this example:

const data = [
  {
    oid: "nbfwm6zzd3s00",
    name: ""
  },
  {
    oid: "g74rvmr3cxpc0",
    name: ""
  }
];

const myObj = {
  nbfwm6zzd3s00: "test value 1",
  g74rvmrcxpc0: "test value 2"
};

for (const key of Object.keys(myObj)) {
  data.forEach((d) => {
    if (key === d.oid) {
      console.log("Found: ", key);
    }
  });
}

CodePudding user response:

const data = [
  {
    oid: "nbfwm6zzd3s00",
    name: ""
  },
  {
    oid: "g74rvmr3cxpc0",
    name: ""
  },

];

const myObj = {
  nbfwm6zzd3s00: "test value 1",
  g74rvmrcxpc0: "test value 2"
};



console.log( data.filter(item => Object.keys(myObj).includes(item.oid) ))

CodePudding user response:

data.map(d => d.oid).some(value => value in myObj)

should do it. Test:

const data  = [
    {
        "oid": "nbfwm6zz3d3s00",
        "name": "",
    },
    {
        "oid": "g74rvmr3cxpc0",
        "name": "",
    }
];
const myObj = {
  nbfwm6zzd3s00: "test value 1",
  g74rvmrcxpc0: "test value 2"
};

console.log(data.map(d => d.oid).some(value => value in myObj))

Seems legit, since 'nbfwm6zz3d3s00' !== 'nbfwm6zzd3s00' and 'g74rvmr3cxpc0' !== 'g74rvmrcxpc0'

Once any of the pairs are matched, it returns true.

  • Related