0

My array has mixed values. Some are strings and some are numbers. My array is

['Yoghurt', 48, 'Rice', 138, 'Apple', 52]

And I want my output:

{ Yoghurt: 48, Rice: 138, Apple: 52 }

Where every odd index is the property and every even index is the key. I've noticed that using Object.fromEntries will not work because my error is 'Yoghurt' is not an entry object.

  • You need to loop through the array and build the object yourself – Gowtham Raj J Mar 13 '21 at 06:39
  • 1
    [Duplicate](https://google.com/search?q=site%3Astackoverflow.com+js+from+flat+key+value+array+create+object+-flatten) of [Convert flat array \[k1,v1,k2,v2\] to object {k1:v1,k2:v2} in JavaScript?](https://stackoverflow.com/q/8751034/4642212). Use a variant of `yourArray.reduce((result, token, index, array) => (index % 2 === 0 ? (result[token] = array[index + 1], result) : result), {});`. – Sebastian Simon Mar 13 '21 at 06:44
  • function main(foods) { let obj = {}; while (foods.length) { obj[foods.shift()] = foods.shift(); } console.log(obj) } Thanks. This one seemed to work. Does anyone know another way to solve this? :) – purpleorbiter63 Mar 13 '21 at 06:53

0 Answers0