Home > Back-end >  How do I filter an array of objects ? The obejcts have an email property. I want to get a new array
How do I filter an array of objects ? The obejcts have an email property. I want to get a new array

Time:10-11

I have this array

let registers = [Register, Register, Register];

and

Register {name: 'Ray', email: '[email protected]', password: '1234'}
Register {name: 'Carl', email: '[email protected]', password: '4321'}
Register {name: 'Lina', email: '[email protected]', password: '5678'}

How can I get a new array with the objects that have @gmail.com as email ?

CodePudding user response:

You can use enter image description here

const data = [
  { name: "Ray", email: "[email protected]", password: "1234" },
  { name: "Carl", email: "[email protected]", password: "4321" },
  { name: "Lina", email: "[email protected]", password: "5678" },
];

const output = data.filter((o) => o.email.match(/@gmail\.com$/));

console.log(output);

CodePudding user response:

Use Array.filter with String.includes.

Array.filter filters the original array with some condition, where String.includes provides the condition, the email includes a string @gmail.com

const data = [{ name: 'Ray', email: '[email protected]', password: '1234' },
              { name: 'Carl', email: '[email protected]', password: '4321' },
              { name: 'Lina', email: '[email protected]', password: '5678' }];

const output = data.filter(node => node.email.includes('@gmail.com'));;

console.log(output);

  • Related