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

150
Views
Collect key value pair from array of objects Javascript

I have an array of objects in Javascript and I want to collect just the given key and value from the list. How would one do this? I feel like I have over engineered the solution but maybe not.

I wasn't sure if there was a cleaner way of doing this.

The results should be a list of objects containing just the key 'id' and id 'value'.

const items = [{
    id: "45054",
    name: "Brittany"
  },
  {
    id: "8980",
    name: "Amber"
  },
  {
    id: "9843",
    name: "Leslie"
  },
  {
    id: "45306",
    name: "Doug"
  },
  {
    id: "7863",
    name: "Kevin"
  },
]

let ids = []

for (let i = 0; i < items.length; i++) {
  ids.push({
    id: items[i].id
  })
}

console.log(ids)

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

0

that isn't bad, I personally would just use map:

let ids = items.map(item => ({id: item.id}));
about 4 years ago · Juan Pablo Isaza Report

0

A cleaner way would be using Array.prototype.map(). Your answer is certainly not a wrong way to do so, though.

const items = [{
    id: "45054",
    name: "Brittany"
  },
  {
    id: "8980",
    name: "Amber"
  },
  {
    id: "9843",
    name: "Leslie"
  },
  {
    id: "45306",
    name: "Doug"
  },
  {
    id: "7863",
    name: "Kevin"
  },
]

const ids = items.map(x => ({id: x.id}));
console.log(ids)

about 4 years ago · Juan Pablo Isaza Report

0

To deal with this you can use map like Pranev said, but if you want to have a more specific solution based on any other key, you can play with Object.keys, and then use the key that you want to get the id or any other key.

    const items = [
  {
    id: "45054",
    name: "Brittany",
  },
  {
    id: "8980",
    name: "Amber",
  },
  {
    id: "9843",
    name: "Leslie",
  },
  {
    id: "45306",
    name: "Doug",
  },
  {
    id: "7863",
    name: "Kevin",
  },
];

let ids = [];

for (let i = 0; i < items.length; i++) {
  const keys = Object.keys(items[i]);
  keys.forEach((key) => {
    if (key === "id") {
      ids.push({
        id: items[i][key],
      });
    }
  });
}
console.log(ids);
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!