The problem with the above code is that, firstly, the function returns nothing, and secondly, the initial value was an array. Therefore, it is strange to expect an object at the exit.
After correcting these errors, you can go to the convolution algorithm.
In fact, inside one reduce should be located the second one, which would add values from the current object to the resulting one.
To do this, you can use both the .keys
method .keys
returns an array of keys, which can then be collapsed into an object, specifying the initial value in result
, and the .entries
method .entries
which also returns an array whose elements are a key-value pair.
The final code might look like this:
var t = [{ k1: 'v1' }, { k2: 'v2' }, { k3: 'v3' }]; function arrayToObject(array) { return array.reduce(function(result, item) { return Object.keys(item).reduce((r, key) => { result[item[key]] = key; return result; }, result); }, {}); } console.log(arrayToObject(t));
Or so:
var t = [{ k1: 'v1' }, { k2: 'v2' }, { k3: 'v3' }]; function arrayToObject(array) { return array.reduce(function(result, item) { return Object.entries(item).reduce((r, [key, value]) => Object.assign(result, { [value]: key }), result); }, {}); } console.log(arrayToObject(t));