convert array to object the output should be same as key and value.
sample array:(my input structure)
var a = [1,2,3,4,5];
I need this structure of output:
{
'1': 1,
'2': 2,
'3': 3,
'4': 4,
'5': 5
}
Use lodash's _.keyBy()
:
const result = _.keyBy([1, 2, 3, 4, 5]);
console.log(result);
<script src="https://cdnjs.cloudflare.com/ajax/libs/lodash.js/4.17.11/lodash.js"></script>
You don't need a library for that, just a standard reduce:
let obj = [1,2,3,4,5].reduce((o,k)=>(o[k]=k,o), {})
I use reduce here
const listToObject = list => list.reduce((obj, key) => {
return {
...obj,
[key]:key
}
}, {})
console.log(listToObject([1,2,3,4,5]))
You can use Object.fromEntries()
with Array.map()
:
var a = [1,2,3,4,5];
console.log(
Object.fromEntries(a.map(v => [v, v]))
)
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With