Home > Back-end >  turning an array with two indexes into an object where {array[0] : array[1]}
turning an array with two indexes into an object where {array[0] : array[1]}

Time:12-02

I am trying to turn this: const arr = ['last_updated_epoch', 1669949100] into

 {'last_updated_epoch': 1669949100}

I tried:

const arr = ['last_updated_epoch', 1669949100]

arr.reduce((a, v) => ({ ...a, [v]: v}), {})

but i get this:

{1669949100: 1669949100, last_updated_epoch: 'last_updated_epoch'}

and I want to get this:

{'last_updated_epoch': 1669949100}

so i can push it in an empty array and use array methods

CodePudding user response:

Seems you have make things complicated,why not use let result = { [arr[0]] :arr[1] } directly?

const arr = ['last_updated_epoch', 1669949100]

let result = { [arr[0]] :arr[1] }
console.log(result)

CodePudding user response:

Something like this

for (let i = 0 , i < arr.length - 1, i  ) {
  let obj = {};
  obj[arr[i]] = arr[i 1]
}
  • Related