How to convert javascript array to object

Quajo Duke

I have an array const arr = ['boy', '2', 'girl', '25', 'dog', '6'] and I want to convert it to and object so it will be come newCreatedObject = {'boy': '2', 'girl': '25', 'dog': '6'}.

Here is what i have tried:

const newCreatedObject = arr.reduce((acc, cur, i, arr) => {
      return {...acc, [cur]: arr[i + 1]};
    }, {})

This is what I get {'6': undefined, '25': 'dog', '2': 'girl', 'boy': '2', 'girl': '25', 'dog': '6'}

the result I want is coming at the later of the object

Nina Scholz

You need to take only each second element for the result.

const
    array = ['boy', '2', 'girl', '25', 'dog', '6'],
    object = array.reduce(
        (acc, cur, i, arr) => i % 2
            ? { ...acc, [arr[i - 1]]: cur }
            : acc,
        {}
    );

console.log(object);

Collected from the Internet

Please contact [email protected] to delete if infringement.

edited at
0

Comments

0 comments
Login to comment

Related

how can i convert object into an array in javascript?

How to convert JSON object to JavaScript array?

How to convert json to array object in javascript?

How to convert array to object in Javascript?

How to Convert nested json to array of object in Javascript?

javascript how to convert array into object

How to convert array of objects to object of array in javascript?

How to convert Object into array in jquery/javascript

How to convert JSON Object into Javascript array

How to convert array object to arguments in javascript

How I can convert array to object in Javascript

How to convert an object from PHP to an Array in Javascript?

How to Convert Object to Array in Javascript

Convert array to object in JavaScript

How to convert an object with property and key to Array in JavaScript?

how to convert this JavaScript object that contains an array to JSON?

How to convert an array of JSON into an array of javascript object?

How to convert array into specif object in javascript?

how convert array to object with specific key in javascript

How to convert a JavaScript array to an object?

How to convert url array query to object in Javascript

how convert my nested object to array in javascript

How to convert nested object to array of object in javascript?

How to convert array in Object in JavaScript?

How to convert an object to array of multiple objects in javascript

how to convert a javascript object to an array of 1 eliment?

How to convert array to object and assign value in Javascript?

How to convert JSON array to OBJECT array javascript?

How to convert an object which can be array or single object to an array in javascript