Easily transform arrays into objects by dynamically changing the keys

I have a comma-separated list that looks like this:

var arr = [1,2,3,4]

and I want to transform it into the following format:

var new_arr = [
 {x:1, y:2},
 {x:3, y:4}
]

I'm having trouble figuring out how to achieve this key/value transformation.

Answer №1

For a solution, you can utilize the Array.reduce() method to achieve the desired outcome.

To implement the logic, consider adding a new element to the result if the index is even, otherwise, proceed to the next iteration.

const input = [1,2,3,4]
 
const result = input.reduce((acc, el, idx, arr) => { 
    return (idx % 2) ? acc : [...acc,  { x: el, y: arr[idx + 1]} ];
}, []);
 
console.log('Result:', result);
.as-console-wrapper { max-height: 100% !important; }

Answer №2

One approach you could take is illustrated in the following example:

To start, iterate over the array and check if the modulus value of the current index is not equal to 0. If it is not, return an empty object (which will be filtered out later). Otherwise, return a new object with the current element as y and the previous element in the array (referenced by index) as x.

const x = [1,2,3,4,5]

const g = x.map((el, i) => {
  if(i%2) {
    return {
      x: x[i - 1],
      y: el
    }
  }
  return {}
}).filter(t => Object.keys(t).length)

console.log(g)

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

Is it possible to define a Divider or Header within the options array for the dropdown component in Semantic UI React?

Currently, I'm incorporating ReactJS along with SemanticUI for ReactJS to enhance the appearance of my front end. My query pertains to whether it is feasible to define a header or divider within the options array of objects for a dropdown component? ...

Setting the content-type for static assets in NuxtJS

I'm trying to use the Nuxt built-in server to serve the static file /.well-known/apple-app-site-association with a content-type of application/json. Unfortunately, because the file does not have a .json extension, it is returning as application/octet- ...

After AngularJS has loaded, CSS animations seem to be ineffective

When loading a page, I have created a div that is displayed. Here is the code: <div ng-show="load" class="rb-animate-time rb-animate-hide rb-load"> <div class="text">Hello world</div> </div> <div ng-init="load = false">&l ...

Node 19820 threw an uncaught promise rejection warning due to a TypeError stating that it cannot read the property 'byteLength' of an undefined value

I'm currently working on developing an API with the use of Express to enable the upload of images to Firebase storage. However, whenever I try to access this particular endpoint, an error message is displayed: "(node:19820) UnhandledPromiseRejectionWa ...

Assistance required with Jquery logic for managing different divs with individual triggers. Ensure only one div is open at a time and close all others when a new one is opened

http://jsfiddle.net/nicktheandroid/ZSvHK/ I am facing some challenges with my current code and would appreciate any suggestions for improvement. Here are the issues I am encountering: I have a set of divs, each with its own trigger button. Only one menu ...

The react form fails to properly store user input within a formik fieldarray

I have encountered an issue with sending data from text boxes within a field array using Formik. The buttons for adding and deleting fields are working correctly, and data can be entered into the text boxes. However, when the form is submitted, the data en ...

What is the proper way to employ if and else if statements within Angular2?

Here's a question that has been duplicated on my How to utilize *ngIf else in Angular? post! ...

Can you explain the significance of the '#' symbol within the input tag?

I was reading an article about Angular 2 and came across a code snippet that uses <input type='text' #hobby>. This "#" symbol is being used to extract the value typed into the textbox without using ngModal. I am confused about what exactly ...

Sorting a function with two parameters in descending order is possible even when dealing with an empty array and no initial value for reduction

My npm test is not passing the third out of six tests. I have attempted to sort it using the following code snippet: sumAll.sort(function(min,max)) { return max - min; } However, this approach did not work. I also tried incorporating conditionals in t ...

Guide to running a NextJS app alongside an Express server backend on the same localhost port

I'm working on hosting my NextJS app, which is built with React, on the same localhost port as my express api-server backend. Within my express server API settings, I have configured my API server to listen on: http://localhost:3000/graphql How can ...

Unable to trigger ActionFunction with Remix and MUI slider

I am trying to implement a MUI slider in order to update a database by using Remix ActionFunction. The issue I am facing is that when the MUI slider is moved, it reloads the default function instead of calling the ActionFunction. How can I make it trigger ...

Issue encountered while attempting to send an HTML file using express.js

I have been trying to display an HTML file using Express.js with a static __dirname, but the HTML content does not show up after calling localhost/ var express = require('express'); var web = express(); ...

A strategy for concealing the selected button within a class of buttons with Vanilla JS HTML and CSS

I have encountered a challenging situation where I am using JavaScript to render data from a data.json file into HTML. Everything seems to be functioning correctly, as the JSON data is being successfully rendered into HTML using a loop, resulting in multip ...

What sets apart object destructuring from destructuring assignment?

Consider this scenario where we have an object: let obj = { a: 1, b: 2 } let { a, b } = obj; console.log(a, b); // output 1, 2 Now, let's examine a different case where 'a' and 'b' are already initialized: let obj = { a: 1, b: 2 ...

What could be causing the getTotals() method to malfunction?

I have been working on a finance app that is designed to update the "income", "expenses", and "balance" tables at the top each time a new item is added by the user. However, the current code seems to be failing in updating these values correctly based on u ...

Encountered AxiosError: parameters need to be in the form of an object: 'ERR_BAD_OPTION_VALUE'

I am facing a challenge with passing an array as a parameter in an axios get request within a React application using the latest packages. Despite trying various solutions from similar issues, I have experimented with two different methods/syntax forms, a ...

Utilizing a class instance as a static property - a step-by-step guide

In my code, I am trying to establish a static property for a class called OuterClass. This static property should hold an instance of another class named InnerClass. The InnerClass definition consists of a property and a function as shown below: // InnerC ...

What could be causing the default dropdown option to vanish once another selection is made?

Check out this GIF to illustrate my query. Is there a way to ensure that when an option is selected, the default choice "Watching" appears in the dropdown menu? For the direct link to the codepen, click here. <!DOCTYPE html> <html lang="en& ...

Unable to utilize Socket.io version 2.0.3

When it comes to developing a video chat app, I decided to utilize socket.io. In order to familiarize myself with this library, I followed various tutorials, but unfortunately, I always encountered the same issue. Every time I attempted to invoke the libr ...

Exploring the function.caller in Node.js

Currently, I have a task that relies on function.caller to verify the authorization of a caller. After reviewing this webpage, it seems that caller is compatible with all major browsers and my unit tests are successful: https://developer.mozilla.org/en-U ...