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