I am new to Javascript.
I need to write a function to covert an array of objects to an object with a given key.
The input is like this
convert([{id: 1, value: 'abc'}, {id: 2, value: 'xyz'}], 'id')
and output needs to be like this
{
'1': {id: 1, value: 'abc'},
'2': {id: 2, value: 'xyz'}
}
I have tried the below code.
When I am trying this directly in console it seems it is working.
var arr = [{ id: 1, name: 'John', role: 'Developer'},
{ id: 2, name: 'Jane', role: 'Lead'},
{ id: 3, name: 'Robbie', role: 'QA'}];
let res = arr.reduce((prev, current) => {
prev[current.v] = current;
return prev;
}, {})
console.log(res)
But, when I am trying do it from the function it is not working.
function f(k, v) {
//console.log(k);
k.reduce((prev, current) => {
prev[current.v] = current;
return prev;
console.log(prev)
}, {})
}
f(arr, 'role');
Any help will be highly appreciated.