Transform an array into an object, organizing values according to their even or odd index positions

I need help converting an array into an object where the keys are based on whether the index of the array is odd or even.

For example:

Input: ["name", "Tom", "age", 20]

Output: {"name": "Tom", "age": 20}

I know this can be achieved using basic JavaScript functions like forEach, map, and filter, but I'm looking for a simpler solution.

I've explored the underscore.js documentation, but couldn't find a suitable method. Is there an easier way to accomplish this task?

Answer №1

Here's my take on it:

Efficient and straightforward loop solution:

const basicArray = ["title", "John", "age", 30];

// Customizing the Array object
Array.prototype.convertToObject = function() {
    let result = {};

    for(let index = 0; index < this.length; index += 2) {
        let key = this[index], value = this[index + 1];
        result[key] = value;
    }

    return result;
}

// Alternatively, as a standalone function
const convertToObject = arr => {
    let result = {};

    for(let index = 0; index < arr.length; index += 2) {
        let key = arr[index], value = arr[index + 1];
        result[key] = value;
    }

    return result;
}

const basicObjectOne = basicArray.convertToObject(); // Using the prototype method
const basicObjectTwo = convertToObject(basicArray); // Utilizing the standalone function

Answer №2

If you want to assign elements to keys based on a condition, you can utilize Array#forEach along with an index check. If the index is odd, then pair the element with the key from the previous item.

var array =  ["name", "Tom", "age", 20],
    object = {};

array.forEach(function (a, i, aa) {
    if (i & 1) {
        object[aa[i - 1]] = a;
    }
});

console.log(object);

You can achieve the same result using Array#reduce.

var array =  ["name", "Tom", "age", 20],
    object = array.reduce(function (r, a, i, aa) {
        if (i & 1) {
            r[aa[i - 1]] = a;
        }
        return r;
    }, {});

console.log(object);

Answer №3

Code snippet using underscores:

output = _.object(..._.partition(input, (_, i) => !(i % 2)))

The _.partition function divides the input array into two subarrays: one for keys and one for values. We then use _.object to create an object from these key-value pairs.

If you prefer functional and semantic code:

const even = i => !(i % 2);
const index = fn => (_, i) => fn(i);

output = _.object(..._.partition(input, index(even)))

Another approach is the recursive solution:

function arrayToObject([prop, value, ...rest], result = {}) {
  return prop ? arrayToObject(rest, Object.assign(result, {[prop]: value})) : result;
}

For those who prefer an iterative method:

function arrayToObject(arr) {
  const result = {};
  while (arr.length) result[arr.shift()] = arr.shift();
  return result;
}

Answer №4

An alternative approach is to utilize the reduce method:

var data = ["name", "Alice", "age", 30],
    result = data.reduce((previous, current, index, array) => (index % 2 ? previous[array[index - 1]] = current : previous[current], previous),{});
console.log(result);

This particular operation can also be achieved using the reduce function.

Answer №5

let data = ["product", "phone", "price", 500] ;
let result = {}
data.forEach((item, index, array) => {
  if (index % 2 === 0) result[item] = array[index+1];
});
console.log(result); //{ product: 'phone', price: 500 }

Answer №6

An example of a for loop with conditional assignment

var elements = ["element1", "value1", "element2", 42, "element3"];
var dictionary = {};
for (var index = 0; index < elements.length; index += 2){
    //First iteration: assign dictionary["element1"] to "value1"
    //Second iteration: assign dictionary["element2"] to 42
    //Third iteration: assign dictionary["element3"] to "" since elements[5] is undefined
    dictionary[elements[index]] = elements[index + 1] || "";
}

Answer №7

const array = ["name", "Tom", "age", 20, "address", "London"];

function extractParams([key, value, ...remaining]) {
  return key ? { [key]: value, ...extractParams(remaining) } : {};
}

console.log(JSON.stringify(extractParams(array), null, 3));

// For example, in node js to obtain arguments in this way
// extractParams(process.argv.slice(2));

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

Inject Custom ASP Control Script into the DOM dynamically upon registration

During a postback, I am loading my ascx control when a dropdown change event occurs. Parent C#: private void ddlChange() { MyControl myCtr = (CallScript)Page.LoadControl("~/Controls/MyControl.ascx"); myCtr.property = "something"; // setting publ ...

How to differentiate between two arrays in ReactJS

Can someone help me with this code in reactjs? Here is the link to it: http://codepen.io/fernandooj/pen/MJOodr 1- I have an array that I am mapping, and for each item, I am sending a checkbox 2- There is another array that I still need to define 3- I want ...

Combining Socket.io with AJAX for real-time web applications

I am currently working on a web application that relies on Socket.io for delivering notifications to users. I'm wondering if it would be more beneficial to utilize Socket.io exclusively for all client-server communication, or if mixing in traditional ...

Issue with the Release build failure involving the Linker and ___gxx_personality_v0"

In my pursuit of running my application offline on my phone using react-native v0.40, I attempted creating a Release build. Unfortunately, this resulted in errors causing the app to fail starting on my phone (although it runs successfully on the simulator) ...

Refusing to allow any alterations to the form until it has been saved

I have a form with various input elements such as text input, radio buttons, and a select dropdown. My goal is to allow the selection of a radio button only once at a time. If the user selects the same radio button again, I want to prevent it unless they ...

Determine the number of rows in the Tabulator's table

Can anyone tell me how to retrieve the number of rows in a table created using Tabulator on a website? Is there a method like table.size or table.length that I can use for this purpose? The table has been initialized with the following code: table = new T ...

Exploring AngularJS JSON Parsing Techniques (such as utilizing ng-repeat)

My approach to processing json data looks like this: $scope.activities = response.data; console.log($scope.activities.length); var list = []; for (var i = 0; i < $scope.activities.length; i++) { console.log($scope.activities[i].name); list.pus ...

Discover how to verify the existence of an image within your local system by implementing AJAX technology

I have an image located in D:\img\need.png and I need to check if it exists or not. When attempting to do so with the following code, the error method is always called. $.ajax({ url:'http://www.himansuit.com//modiyojana.jpg', ...

Tips for resolving an issue with an overflowing Uber React-Vis multicolor bar chart

I am trying to create a multi-colored bar chart using Uber's react-vis library. However, I am encountering an issue where the leftmost bar of the chart is overflowing below the YAxis instead of remaining contained to the right of it. You can view the ...

What is the most effective method for dividing a string in TypeScript?

Here is the scenario: receiving a string input that looks like Input text: string = "today lunch 200 #hotelname" Output subject: "today lunch" price: 200 tag: #hotelname My initial solution looks like this: text: string = "today lunch 200 #hotelname" ...

Navigating with Angular 2: Expressing HTML 5 Routing Challenges

I'm currently working on a simple web application using Express 4 and Angular 2. The only Angular 2 specific aspect in this project is the utilization of its HTML5 router. Let me walk you through how the routing works in this app: There are two prim ...

Troubleshooting Vue.js dynamic image path loading issues

Struggling to dynamically load images in a single file component, I keep encountering an error stating that the module cannot be found. It seems like I'm attempting something similar to what was discussed in this post on Stack Overflow, but I can&apos ...

The value of req.user is not defined in a stack involving node, express, passport,

When I use console.log(req.session); I receive the message: Session {cookie:{ path: '/',_expires: null,originalMaxAge: null,httpOnly:true },passport: { user: 5b427a2d117d7c3f6087db8a } } However, when using console.log(req.user); I get un ...

Exploring the power of Partial Views in ASP.NET MVC 4 with Ajax.ActionLink

On my homepage, I am attempting to incorporate links that will render partial views - revealing information from the database when clicked. I want the link to be replaced by text on the same page. Despite following a tutorial, I am facing challenges in get ...

What steps should I take to retrieve a value from a Headless-UI component?

I have integrated a Listbox component from Headless-UI in my React project. The Listbox is contained within its own React component, which I then include in a settings form. How can I extract the selected value from the Listbox component and save it to th ...

What is the process for specifying a datatype in a MySQL column that is used to store an array?

I'm currently Java programming and facing a challenge with an input dialog setting attributes in columns. One of the columns is named "Notes" and it needs to receive an array. Here are my current columns: Name: (patient's name), [varchar]. CPF: ...

What causes an error when attempting ++[] but produces 1 with ++[[]][0]?

Can you explain the difference between the following two expressions? It appears that incrementing [] is equivalent to incrementing [[]][0] since the first element of this outer array is []. console.log(++[]); console.log(++[[]][0]); ...

Troublesome CSS Zoom causing issues with jQuery scrollTop

As I design a website that has a fixed width and zooms out on mobile browsers, I've opted to adjust the zoom using CSS rather than viewport meta tags: html, body { zoom: 0.8; } It's been effective so far, but now I'm facing an issue wi ...

What is causing my Javascript media query for the sidebar to not function properly?

I am working on implementing a sidebar that slides out 250px using JavaScript on the desktop view. However, I want the sidebar to take up 100% width when viewed on mobile devices. Despite my attempts to use Media Queries in JavaScript to achieve this, I am ...

Issue with MUI Data Grid sorting: Data Grid sortComparator function returning undefined

I'm attempting to organize data with nested values in a data grid, but I keep receiving 'undefined' on the sortComparator of Data Grid Columns. Code: Column Data Setup: { headerName: 'Title', field: `${this.props.type} ...