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

163
Views
Array of objects convert to object with keys by item field value

I have this array:

const demo = [
  { key: 'apple', a: 'b', c: 1 },
  { key: 'banana', a: 'f', c: 3 },
  { key: 'orange', a: 'j', c: 8 },
];

I can get info about "banana" by using:

demo.find(item => item.key === 'banana')

Instead I would like to have this associative and access like this:

demo.banana.c

So I need to somehow get this:

const demo = {
  'apple': { key: 'apple', a: 'b', c: 1 },
  'banana': { key: 'banana', a: 'f', c: 3 },
  'orange': { key: 'orange', a: 'j', c: 8 },
};

Or without "key" inside, it does not matter.

What would be simplest solution? Some simple (maybe one-line) approach with ES6? If not, Lodash instead?

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

0

const demo = [{
    key: 'apple',
    a: 'b',
    c: 1
  },
  {
    key: 'banana',
    a: 'f',
    c: 3
  },
  {
    key: 'orange',
    a: 'j',
    c: 8
  },
];

const solution = demo.reduce((acc, cur) => {
  acc[cur.key] = cur;
  return acc
}, {})

console.log(solution)

about 4 years ago · Juan Pablo Isaza Report

0

You could use Object.fromEntries to build the object, and destructuring to extract the key from the rest of the original object:

const demo = [
  { key: 'apple', a: 'b', c: 1 },
  { key: 'banana', a: 'f', c: 3 },
  { key: 'orange', a: 'j', c: 8 },
];

let result = Object.fromEntries(demo.map(({key, ...rest}) => [key, rest]));

console.log(result);

about 4 years ago · Juan Pablo Isaza Report

0

You use lodash's _.keyBy():

const demo = [
  { key: 'apple', a: 'b', c: 1 },
  { key: 'banana', a: 'f', c: 3 },
  { key: 'orange', a: 'j', c: 8 },
];

const result = _.keyBy(demo, 'key');

console.log(result);
<script src="https://cdnjs.cloudflare.com/ajax/libs/lodash.js/4.17.21/lodash.min.js" integrity="sha512-WFN04846sdKMIP5LKNphMaWzU7YpMyCU245etK3g/2ARYbPK9Ub18eG+ljU96qKRCWh+quCY7yefSmlkQw1ANQ==" crossorigin="anonymous" referrerpolicy="no-referrer"></script>

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!