Home > other >  How can I get a key value from an array that has object inside
How can I get a key value from an array that has object inside

Time:03-15

Imagine I have something like this:

const myArray = [
    {
        Email:[email protected],
        Password:1234,
        Username:myname
    }
]

How can I access email value inside of object in easier way? I know can do some looping or mapping then using for of or something like that but is there any better way?

I want to do a check like that:

const otherArray = [
    {
        Email:[email protected],
        Username:myname,
        Password:1234
    }
]

If the Email value inside of myArray is equals to the value of otherArray then if it does:

  • return true

CodePudding user response:

Some examples (with the syntax error fixed on the values)

let myname = "I create sntax errors";
const myArray = [{
  Email: "[email protected]",
  Password: "1234",
  Username: myname
}];

const otherArray = [{
  Email: "[email protected]",
  Username: myname,
  Password: "1234"
}];

const otherArrayAlso = [{
  Email: "[email protected]",
  Username: myname,
  Password: "1234"
}];
let isMatch = myArray[0].Email == otherArray[0].Email;
console.log(myArray[0].Email, otherArray[0].Email);
console.log("IsMatch:", isMatch);
console.log(myArray[0].Email == otherArrayAlso[0].Email);

CodePudding user response:

You can simply check like this

const myArray = [
  {
    Email: '[email protected]',
    Age: 30,
  },
  {
    Email: '[email protected]',
    Age: 24,
  },
  {
    Email: '[email protected]',
    Age: 20,
  },
]

const otherArray = [
  {
    Email: '[email protected]',
    Age: 30,
  },
  {
    Email: '[email protected]',
    Age: 24,
  },
  {
    Email: '[email protected]',
    Age: 20,
  },
]

let found = false;

const otherArrayEmails = otherArray.map(item => item.Email);
for (let i = 0; i < myArray.length; i  ) {
   if (otherArrayEmails.includes(myArray[i].Email)) {
      found = true;
      break;
   }
} 
console.log(found)

CodePudding user response:

You can get the email with myArray[0].Email. But first change your array to

const myArray = [
    {
        'Email': '[email protected]',
        'Password': 1234,
        'Username': 'myname'
    }
]
  • Related