Integrating array elements into the keys and values of an object

Given the array below:

const Array = ['Michael', 'student', 'John', 'cop', 'Julia', 'actress']

How can I transform it into an object like this?

const Object = {
Michael: student,
John: cop, 
Julia: actress,
}

Is there a way to assign even index elements as keys and odd index elements as values in the resulting object?

Answer №1

To achieve the desired result, you can use a simple for loop that iterates through the array by two indexes at a time.

Here's an example:

const array = ['Michael', 'student', 'John', 'cop', 'Julia', 'actress'];

const output = {}

for(let i = 0; i < array.length; i+=2){
  output[array[i]] = array[i+1]
}

console.log(output);

Answer №2

const people = ['Michael', 'student', 'John', 'cop', 'Julia', 'actress'];

let data={};

people.forEach((item, index) => {

  if(index % 2 === 0){

    data[item] = people[index+1];

  }
})

console.log(data);

Answer №3

A method to consider is dividing the array into chunks of 2 and then transforming it into an object using Object.fromEntries.

let arr = ['Michael', 'student', 'John', 'cop', 'Julia', 'actress'];
let obj = Object.fromEntries([...Array(arr.length / 2)]
            .map((_, i)=>arr.slice(i * 2, i * 2 + 2)));
console.log(obj);

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Updating Variable Values in PHP

Currently, I am working on a project about online shopping using PHP. However, I have encountered an issue regarding changing the currency value. I need to convert the currency to another based on the exchange rate provided. <select onchange=""> ...

How can one identify a concealed glitch that exclusively occurs for a particular individual or hardware in a React environment?

Is it possible to identify a bug that occurs only with a particular individual or hardware in a React application? This bug is invisible and never appears during tests, but only manifests with a specific client within my company. Do you have any tips on h ...

Seeking assistance with producing results

Is there someone who can provide an answer? What will be the output of the code snippet below when logged to the console and why? (function(){ var a = b = 3; })(); console.log("Is 'a' defined? " + (typeof a !== 'u ...

Converting numbers in React Native, leaving only the last four digits untouched

When mapping biomatricData.ninId, the value I am receiving is "43445567665". biomatricData.ninId = 43445567665 My task now is to display only the last 4 digits and replace the rest with "*". I need to format 43445567665 as follows: Like - *******7665 ...

Is it possible to load a JS file without using the require function?

Is there a method to load a JavaScript file without using require, but with fs for instance? I am aware that for JSON files I can utilize: const jsonFile = JSON.parse(fs.readFileSync("/jsonfile.json")) Can the same be done for a JavaScript file? I am inq ...

Toggle visibility of div based on current business hours, incorporating UTC time

UPDATE I have included a working JSFiddle link, although it appears to not be functioning correctly. https://jsfiddle.net/bill9000/yadk6sja/2/ original question: The code I currently have is designed to show/hide a div based on business hours. Is there a ...

Enable Row Editing with a Click in Material Table

Utilizing the material-table library, I am implementing a feature to enable table rows to be editable upon double-click. The goal is for clicking on a row to trigger the same action as clicking the edit button located in the actions column on the leftmost ...

WebStorm 6 does not recognize the post method in Node.js Express

I recently started learning about node.js and decided to experiment with the express module in my application. Everything was going well until I attempted to use the app.post method. I am developing my app on WebStorm 6.0.2 and it doesn't seem to reco ...

Expanding a JSON data structure into a list of items

In my Angular service script, I am fetching customer data from a MongoDB database using Django: getConsumersMongodb(): Observable<any> { return this.httpClient.get(`${this.baseMongodbApiUrl}`); } The returned dictionary looks like this: { &q ...

"Building a tree structure from a one-dimensional array in Angular: A step-by-step

I would like to implement a tree structure in Angular using flat array data and I am willing to explore different packages for rendering the tree. Users should be able to click on a node to view details such as node ID and title. The tree should initially ...

Instructions on invoking a function from one controller within another controller

Is it possible to invoke a function from one controller in another controller? I attempted the following but encountered failure: <div ng-app="MyApp"> <div ng-controller="Ctrl1"> <button ng-click="func1()">func1</button> ...

I am attempting to gather user input for an array while also ensuring that duplicate values are being checked

Can someone assist me with the following issue: https://stackblitz.com/edit/duplicates-aas5zs?file=app%2Fapp.component.ts,app%2Fapp.component.html I am having trouble finding duplicate values and displaying them below. Any guidance would be appreciated. I ...

Issues with Braintree webhooks and CSRF protection causing malfunction

I have successfully set up recurring payments with Braintree and everything is functioning properly. Below is an example of my code: app.post("/create_customer", function (req, res) { var customerRequest = { firstName: req.body.first_name, lastN ...

Decoding JSON on 9gag

I am trying to select a random image from the following URL: In order to display it correctly, I need to determine the size of the image. I am utilizing YQL to store the JSON result in a variable (referred to as source). After replacing 'https&apos ...

Adding a loader to the specific button that has been clicked can be achieved by following these steps:

I am currently in the process of building an e-commerce platform website and I'm looking to implement a feature where users can add products to their cart with just a click of a button. However, before the product is added to the cart, I want to disp ...

What exactly does the statement if(item.some((item) => !item.available) represent in typescript?

Can you explain the meaning of if(item.some((item) => !item.available))? While looking at some code randomly, I came across this snippet: if(item.some((item) => !item.available){ } I'm curious about what it signifies. Can you elaborate on it? ...

Retrieve child and descendant nodes with Fancytree JQuery

I'm currently utilizing Fancytree and have created the following tree structure: root |_ child1 |_ subchild1 |_ subchild2 |_ subchild3 |_ subchild4 When the selected node is child1, I am able to retrieve the fir ...

Establish the directive upon receiving the broadcast

Is there a way to trigger a directive when a specific event occurs on the backend and sets a value to false?... This is where the event is being captured .factory('AuthInterceptor', function($q, $injector, $rootScope) { return { ...

What are some methods for transferring the state variable's value from one component to another in React?

I have the following scenario in my code: there is a Form.js component that interacts with an API, stores the response in the walletAssets state variable, and now I want to create a separate Display.js component to present this data. How can I pass the v ...

What allows for array cells to go beyond the predefined array length?

During my debugging process, I came across an issue involving an integer array of size 0. In a test scenario, I experimented with an array that had more elements inputted than its actual length. int array[0]; for(int i = 0; i < 10; i++) array[i] = ...