Transforming an object into an array of objects with the power of JavaScript

Looking to transform an object with the following structure:

{ From: {"A","B","C"}, To: {"A1","B1","C1"}, value: {1,2,3} }

I need to convert this array:

[
  {from: "A" ,to: "A1" , value: 1  },
  {from: "B" ,to: "B1" , value: 2},
  {from: "C"   ,to: "C1"   , value: 3  }
]

Any suggestions on how to achieve this conversion in JavaScript code?

Answer №1

The input provided is incorrect as it includes an array with key:value pairs and an object without a key:value. The correct format should be

{ From: ["A","B","C"], To:["A1","B1","C1"], value: [1,2,3] }

To achieve the desired outcome, you can utilize the map() function.

let obj = { From: ["A","B","C"], To:["A1","B1","C1"], value: [1,2,3] }

let res = obj.From.map((form,i) => {
  let value = obj.value[i];
  let to = obj.To[i];
  return {form,to,value}
})
console.log(res)

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

div.load() results in a complete page reload

When I save form data, my goal is to load only the specific div without refreshing the entire page. However, despite using the preventDefault() command, the form still seems to be posting the whole page. I have tried adding the following code: $("#btn ...

Exploring the asynchronous nature of componentDidMount and triggering a re-render with force

I am puzzled by the behavior in the code provided. The async componentDidMount method seems to run forceUpdate only after waiting for the funcLazyLoad promise to be resolved. Typically, I would expect forceUpdate to wait for promise resolution only when wr ...

Determining the successful completion of an ajax request using jQuery editable plugin

I recently started using Jeditable to enable inline editing on my website. $(".video_content_right .project_description").editable(BASE_URL+"/update/description", { indicator: "<img src='" + BASE_URL + "/resources/assets/front/images/indicator ...

What is the correct way to initialize a variable that will store the output of setInterval?

While examining a question, I came across someone's solution that proposed updating the code below. In the comments section, it was suggested: Instead of setting this.tm to undefined, we should set it to 0. Since it's a time interval, it shoul ...

Setting up and using npm jshint with Grunt and Node.js

I have successfully installed node.js on Windows with the npm package. My project is located in the D drive at D:>projectD I am currently working on running jshint along with SASS, concat, etc. Everything seems to be working fine except for jshint ...

Is there a way to achieve horizontal alignment for the Twitter and Facebook buttons on my page?

By utilizing the html code provided, I successfully incorporated Twitter and Facebook "Like" buttons into my website. Initially, they were stacked vertically, which resulted in excessive use of vertical space. To optimize space usage, I decided to align th ...

Navigating through parsed JSON with HttpWebResponse

In our WPF application, we are formatting JSON in the following way: { "AccountHistory":[ { "AccountNumber":123456, "DailyEndingBalances": [ {"BalanceDate":"\/Date(14508540000000000)\/","EndingBalance":2511.5 ...

Guidelines for utilizing React to select parameters in an Axios request

As a newcomer to ReactJs, I am working with a Product table on MySQL. I have successfully developed a dynamic table in the front-end using ReactJS along with MySQL and NodeJs on the backend. The dynamic table consists of four columns: Product, Quantity, Pr ...

Difficulty encountered when attempting to utilize keyup functionality on input-groups that are added dynamically

I've exhausted all available questions on this topic and attempted every solution, but my keyup function remains unresponsive. $(document).ready(function() { $(document).on('keyup', '.pollOption', function() { var empty = ...

Issue with Context Menu Not Triggering on Dynamically Added Elements in JQuery

Check out the JSFiddle Demo Within my email sidebar, I implemented a custom right-click feature that allows users to add new sub-folders. The code snippet below demonstrates how this functionality works: if ($(this).hasClass('NewSubFolder')) { ...

Obtain a nested array of objects from Mongoose's Model.find() method and then make modifications to the inner array

I need to retrieve an array of objects with a specific ID from my database within a server route, and then update a property of an object within that array (rather than returning just the objectID, I want to return the Document as an object with the specif ...

Utilize a Sails.js Single Page Application (SPA) to route all unutilized paths to a centralized controller function

I'm currently working on a project where I am building a single page application (SPA) with Sails.js as the backend. My goal is to have all routes redirect to a single controller action. However, the issue I am facing is that when I try the following ...

Retrieve the most recent row from a PHP JSON response

Hey there! I've been attempting to run this code snippet using AngularJS, but all I seem to get is the last row of the dataset. I have come across similar examples on various websites, so I'm not sure if there's a configuration setting that ...

Trouble with loading scripts after transitioning to a new page with AJAX (Barba.js)

Exploring the potential of using AJAX for smooth page transitions. Tried two different methods so far: manually coded transition from () and Barba.js approach (). With both methods, scripts work on initial load but fail to execute when navigating to anot ...

Retrieving values of child elements from JSON using C#

public static void apiCall2() { WebClient c = new WebClient(); var data = c.DownloadString(baseURL + endPoint + "?access_key=" + accessKey + "&currencies=TWD&source=USD&format=1"); //Console.WriteLine(data); JObject api = JObjec ...

Jenkins encountered an error: hudson.remoting.ProxyException caused by net.sf.json.JSONException stating that the JSON String is invalid

I encountered the following error while attempting to parse the JSON file in a Jenkins multibranch pipeline: def payload = writeJSON(file: "hostname.json", json: env.config) json = readJSON file: 'hostname.json' data = new JsonSlurperCl ...

Scraping a few URLs with Javascript for Web Data Extraction

I'm struggling to retrieve data from multiple URLs and write it to a CSV file. The problem I'm facing is that the fetched data is not complete (I expect 10 items) and it's not in the correct order. Instead of getting 1, 2, 3 sequentially, I ...

Issue with Yup and Formik not validating checkboxes as expected

I'm struggling to figure out why the validation isn't functioning as expected: export default function Check() { const label = { inputProps: { "aria-label": "termsOfService" } }; const formSchema = yup.object().shape({ ...

Checking the existence of a user's email in Node.js

Hey there! I am new here and currently learning Node.js with Express. I'm trying to find a way to check if a user's email already exists in the database. Here is what I have so far: const emailExists = user.findOne({ email: req.body.email }); if ...

Error in Mocha test: Import statement can only be used inside a module

I'm unsure if this issue is related to a TypeScript setting that needs adjustment or something else entirely. I have already reviewed the following resources, but they did not provide a solution for me: Mocha + TypeScript: Cannot use import statement ...