0

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?

3 Answers 3

4

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)

Sign up to request clarification or add additional context in comments.

1 Comment

I will accept this question but please provide any explanation, description. Code-only answers are against stackoverflow rules so this answer can be deleted later.
2

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);

Comments

1

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>

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.