I transformed a collection of keys from various arrays into an object for the purpose of sorting, and now I am seeking to convert them back into arrays

let values = selectValues;
    let names = selectNames;
    let priorities = prioritizedHours;
    let prefers = preferHrsArray;
    let years = workedYearsArray;
    let items = values.map((value, index) => {
                           return {
                           value: value,
                           name: names[index],
                           priority: priorities[index],
                           prefer: prefers[index],
                           year: years[index]
                           }
                           });
    let arrayObject = JSON.stringify(items);
    Logger.log('Object array: '+arrayObject);

In this script snippet, I am creating an object from the arrays like names, priorities, etc. Once sorted, the resulting Object looks like this:

[
  {"value":1,"name":"Fiona","prefer":30,"year":6},
  {"value":1,"name":"Martin","prefer":40,"year":7},
  {"value":2,"name":"Adam","prefer":0,"year":20},
  {"value":2,"name":"Steve","prefer":100,"year":5}
]

Now that the sorting is complete, I need to revert back to separate arrays as they were in the original Object. The format of these arrays should be like:

value = [1,1,2,2],
name = ['Fiona', 'Martin','Adam', 'Steve'],
prefer = [30,40,0,100],
year = [6,7,20,5]

Your assistance with this matter is greatly appreciated.

Answer №1

You can iterate through the array using forEach in this scenario

const array = [
  {"value":1,"name":"Fiona","prefer":30,"year":6},            
  {"value":1,"name":"Martin","prefer":40,"year":7},
  {"value":2,"name":"Adam","prefer":0,"year":20},
  {"value":2,"name":"Steve","prefer":100,"year":5}
]

const values = []
const names = []
const prefers = []
const years = []

array.forEach(obj => {
  values.push(obj.value),
  names.push(obj.name),
  prefers.push(obj.prefer),
  years.push(obj.year)
})

console.log(values)
console.log(names)
console.log(prefers)
console.log(years)

Answer №2

This example demonstrates how the map function works in JavaScript:

    const data = [
      { value: 1, name: "Fiona", prefer: 30, year: 6 },
      { value: 1, name: "Martin", prefer: 40, year: 7 },
      { value: 2, name: "Adam", prefer: 0, year: 20 },
      { value: 2, name: "Steve", prefer: 100, year: 5 },
    ];
    
    const values = data.map(x=>x.value);
    const names = data.map(x=>x.name);
    
    console.log(values, names);
    //[ 1, 1, 2, 2 ] [ 'Fiona', 'Martin', 'Adam', 'Steve' ]

To learn more about the map function, visit MDN for details of map

Answer №3

To add some dynamism to your code, consider implementing a solution using the reduce method combined with object destructuring in JavaScript.

const data = [
  {"value":1,"name":"Fiona","prefer":30,"year":6},
  {"value":1,"name":"Martin","prefer":40,"year":7},
  {"value":2,"name":"Adam","prefer":0,"year":20},
  {"value":2,"name":"Steve","prefer":100,"year":5}
];

const {name, value, prefer, year} = data.reduce((accumulated, current) => {
  Object.entries(current).forEach(([key, val]) => {
    if(accumulated[key] == null) 
      accumulated[key] = [];
     
    accumulated[key].push(val);
  });
  return accumulated;
}, {})

console.log(name);
console.log(value);
console.log(prefer);
console.log(year);

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

Utilize anychart.js to define the axis using JSON data

I'm relatively new to using anychart js and encountering some obstacles. I have a json file that is being fetched from an API, containing data on NBA players' statistics. You can find the json file here: My goal is to display the date data on th ...

Utilizing jQuery.ajax to Send an Array of Objects to a PHP Function

In this scenario, an array of objects is represented as follows: rectangle[0].width = w; rectangle[0].height = h; rectangle[1].width = w; rectangle[2].height = h; rectangle[3].width = w; rectangle[3].height = h; ... We need to figure out how to send thi ...

What method can I use to modify an existing decorator directive in AngularJS to automatically select all checkboxes?

After implementing a decorator directive to create a checkbox list following the solution provided in a previous answer on Stack Overflow, where can I find further guidance on adding a main checkbox that toggles the selection of all checkboxes? Is it poss ...

Flag is to be set while moving through the input fields

I am currently working on a form with multiple text fields and a text area. I have implemented a loop to go through each of these fields and check if there is a value present. If the field is empty, I set a flag to pass=false. On the other hand, if a value ...

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! ...

Why isn't the AngularJS injected view resizing to fit the container?

As a novice delving into a project in the MEAN stack, I'm encountering inconsistent HTML previews. When I view it independently versus running it from the project, the display varies. Here's the intended appearance (in standalone preview): imgu ...

Using an `<img>` element as an event handler in a JavaScript function

I'm having trouble setting up a click handler for the search field in my project. I've tried using on() with an img or class, but it's not working as expected. When adding the image using the code below: jQ('#psc').append('&l ...

Show the content of a list from a different URL on a webpage using HTML with the

My current task involves retrieving JSON data using Jquery and then displaying the names in a simple HTML list. Typically, the JSON files I work with have a straightforward format like: [ {a:1,b:2},{a:3,b:4}] However, this time, the JSON file is hosted ...

What is the best way to create an HTML form on-the-fly from a JSON object?

Could someone please assist me in understanding how to dynamically generate an HTML form based on a JSON object using JavaScript? ...

Enhance CSS delivery for the items listed below

Reduce the delay caused by rendering JavaScript and CSS above-the-fold. There are 16 CSS resources currently blocking the rendering of your page. This delay could be affecting the loading time of your content. To improve this issue, consider deferring or ...

Press the AngularJS button using just JavaScript and the element

I've been developing a browser extension that automatically clicks buttons on web pages, but I've run into an issue with sites using AngularJS. The code functions properly on most websites except for those built with AngularJS. Below is the snip ...

Creating DIV's with Equal Heights Using AngularJS ng-repeat

I'm currently facing an issue with aligning two side-by-side divs to the same height when the content is generated using an ng-repeat function. Using flexbox is causing responsiveness issues, and I'm unsure of the appropriate time to call a jQuer ...

Calling a function without specifying its type may lead to issues, especially when dealing with Angular 5 http calls

Currently, my goal is to retrieve data from an API using an interface. I have created a temporary interface as shown below: export interface ITemp { id: number, name: string, age: number } Furthermore, I have an HTTP service where there is a ...

Creating randomized sequences using JavaScript

One of my hobbies involves organizing an online ice hockey game league where teams from different conferences compete. It's important to me that every team gets an equal number of home and away matches throughout the season. To simplify this task, I&a ...

How can I retrieve and store session information during the authorization event in Socket.io with express-sessions?

I have set up a websocket using Socket.io and the express 4 framework on a node.js server. Currently, I am working on implementing an authorization step for my users when they are using the websocket. Upon a user connection, a token is passed as a query ...

What is the process for retrieving an Object from $cookies?

I've encountered an issue where I'm storing a user object on a Cookie and, upon the client's return visit to the site, I want to utilize this object's properties. However, upon the client's return, my cookie object appears as [obj ...

quickest method for attaching a click listener to dynamically added elements in the document object model

When adding multiple elements to the DOM, how can we ensure that these elements also have a click handler attached to them? For instance, if there is a click handler on all elements with the "canvas-section" class, and new "canvas-section" elements are con ...

Having trouble rendering JSON encoded data in a JqPlot Chart within a PHP script

I've spent the past few days scouring through Stack Overflow and various other websites, but I haven't been able to find a solution to my specific issue. Even the book 'Create Web Charts with JqPlot' by Fabio Nelli didn't provide t ...

Extract the Top X elements from a multidimensional array

Consider an Array that consists of nested arrays: [ ["2000-01-01", "<a href="/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="d1a9a8abe091b6bcb0b8bdffb2bebc">[email protected]</a>", 1, 9, 338], ["2000-01-01", "<a href="/ ...

Inquiries about the jQuery Button Timer

Currently experimenting with jQuery to create a timer. Everything seems to be in place and the Stop Timer button is functioning properly. However, I'm facing issues with the Start Timer and Reset Timer buttons as they are not working as expected. Seek ...