Business
Jobs
  • About Us
  • Solutions
    • Job Postings
      Post your job and receive qualified candidates in 48h.
    • Candidate Assessments
      500+ technical and psychological tests, plus anti-fraud.
    • Headhunting
      Tailor-made executive search from start to finish.
    • Payroll + EOR
      Payroll dispersal and EOR across 15+ LATAM countries.
  • Pricing
  • Jobs

0

105
Views
Filter an array of objects according to the name of the key in the objects

I have an array of objects that I want to filter based on the name of the key for those objects. In this particular case I know that there will be one key/value pair for each element in the array.

Assume an array that looks like this:

let dataArray = [
  {
    "name": "David" 
  },
  {
    "location": "New York"
  },
  {
    "name": "Jenna"
  }
]

What I want to end up with is just an array where the key is 'name':

[
  {
    name: "David" 
  },
  {
    name: "Jenna"
  }
]

I've tried various ways of doing this using the filter method, such as this:

const namesArr = dataArr.filter(i => i[key] === 'name');

But none seem to produce the correct result.

about 4 years ago · Juan Pablo Isaza
3 answers
Answer question

0

Use the in operator to check if a property exists on the object:

const dataArray = [{"name":"David"},{"location":"New York"},{"name":"Jenna"}];

// name exists on the object
console.log(dataArray.filter(item => 'name' in item));

// or location doesn't exist on the object
console.log(dataArray.filter(item => !('location' in item)));

about 4 years ago · Juan Pablo Isaza Report

0

You can use the in operator to filter on a particular key being present, see reference.

dataArr.filter(obj => 'name' in obj)

Only checking obj.name would exclude objects where 'name' field is false or null or undefined, even if the property is present on the object.

about 4 years ago · Juan Pablo Isaza Report

0

You can use the object.hasOwnProperty('name') that returns a boolean indicating whether object has a property name

let dataArray = [
  {
    "name": "David" 
  },
  {
    "location": "New York"
  },
  {
    "name": "Jenna"
  }
]

const filtered = dataArray.filter(x => x.hasOwnProperty('name'));

console.log(filtered);

another option is to use the in operator:

let dataArray = [
  {
    "name": "David" 
  },
  {
    "location": "New York"
  },
  {
    "name": "Jenna"
  }
]

const filtered = dataArray.filter(x => 'name' in x);

console.log(filtered);

about 4 years ago · Juan Pablo Isaza Report
Answer question
Find remote jobs

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post vacancy Pricing Sales
Legal
Terms and conditions Privacy policy
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Show me some job opportunities
There's an error!