JavaScript: Transform an Array of Objects into an Array of Objects with Properties

I have a set of incoming data (I've simplified the objects for easier understanding). This data could have hundreds or even thousands of properties.

teams = {
  teams: ['Lakers', 'Clippers', 'Bucks', 'Suns'],
  states: ['California', 'California', 'Wisconsin', 'Arizona']
}

It's important to note that each property will always contain the same number of items.

My goal is to transform this data into an Array List of objects:

teamsList = [
  { teams: 'Lakers', states: 'California' },
  { teams: 'Clippers', states: 'California' },
  { teams: 'Bucks', states: 'Wisconsin' },
  { teams: 'Suns', states: 'Arizona' }
]

This is my initial approach and attempt:

const parseData = (obj) => {
  const teams = obj.teams;
  const states = obj.states;
  let newList = [];
  teams.forEach((item, index) => {
    const teamData = {
      teams: item,
      states: states[index]
    }
    newList.push(teamData);
  })

  return newList;
}

I am curious if there is a more efficient way to accomplish this task?

I forgot to mention that I'm looking for a method where the keys in the new array list can be dynamic too - avoiding having to specifically write out each property:

  teams.forEach((item, index) => {
    const teamData = {
      teams: item,
      states: states[index],
       n: n[index]
    }
    newList.push(teamData);
  })

In this case, n represents any possible object key.

Thank you.

Answer №1

This particular approach functions by initially determining the maximum length of an array, and then dynamically generating new objects based on the keys present in your dataset:

const data = {
  teams: ['Warriors', 'Rockets', 'Bulls', 'Heat'],
  cities: ['San Francisco', 'Houston', 'Chicago', 'Miami']
};

const result = [
  ...Array(Object.values(data).reduce((accumulator, {length}) => Math.max(accumulator, length), 0))
].map((_, i) => Object.keys(data).reduce((accumulator, key) => ({...accumulator, [key]: data[key][i]}), {}));

console.log(result);

Answer №2

Use mapping on one array to locate corresponding values in another array based on index, and then generate an object.

const teams = {
  teams: ['Lakers', 'Clippers', 'Bucks', 'Suns'],
  states: ['California', 'California', 'Wisconsin', 'Arizona']
};
const teamList = teams.teams.map((t, i) => ({ teams: t, states: teams.states[i] }));
console.log(teamList);

If dealing with numerous properties, iterate through the entries for efficient processing.

const teams = {
  teams: ['Lakers', 'Clippers', 'Bucks', 'Suns'],
  states: ['California', 'California', 'Wisconsin', 'Arizona']
};
const entries = Object.entries(teams);
const [key, arr] = entries.shift();
const teamList = arr.map((val, i) => Object.fromEntries(
    [[key, val]].concat(
      entries.map(entry => [entry[0], entry[1][i]])
    )
));
console.log(teamList);

Answer №3

Utilize the Array.map() method to cycle through each element and generate a final array of objects.

teamsData = {
  teams: ['Raptors', 'Warriors', 'Heat', 'Celtics'],
  cities: ['Toronto', 'San Francisco', 'Miami', 'Boston']
};

const processData = (obj) => {
  const cities = teamsData.cities;
  return obj.teams.map((team, index) => ({ team, city: cities[index] }));
}

console.log(processData(teamsData));

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

Formatting Objects and Arrays in React with JavaScript

I previously had access to the first item in my local data using data{0}. However, upon transitioning to a database environment and retrieving the data to create another object, I find myself unable to access the first item using data{0}. It seems like th ...

Can you please explain how the repeat() function functions? I would like to understand it better

Currently diving into the world of Javascript, I came across this interesting method to create a 16X16 grid using example.repeat(number) with a numerical value. While I have a general understanding of the code flow, I'm struggling to fully grasp how t ...

Display a fixed legend on Google Chart without showing percentage values

<script type="text/javascript"> // Loading the Visualization API and the piechart package. google.load('visualization', '1', {'packages':['corechart']}); // Setting a callback to run when the Goo ...

ASP updatePanels causing scrollable grid plugin offsetWidth to be undefined

I am attempting to create scrollable gridviews within update panels by utilizing a function that is called in the pageLoad() function LoadScrollPopupOverridesBehavior() { $('.GridViewPopupWithOverride').Scrollable({ ScrollHeight: 350 ...

What is the best approach for implementing a getworldposition functionality with Three.js?

Looking for a way to create a getWorldPosition function in Three.js that will return a vector? This is the code I have to obtain the World Position of an object (obj) and store it in the vector vec. obj.updateMatrixWorld(); var vec = new THREE.Vector3(); ...

Is it possible to perform a test and decrement simultaneously as an atomic operation?

After tracking down a frustrating bug, I have discovered that it is essentially a race condition. Let's consider a simple document structure for the purpose of this discussion, like { _id : 'XXX', amount : 100 }. There are hundreds of these ...

What method can be employed to eliminate choice selection lacking any value?

Currently, I am encountering difficulties in my attempt to remove or hide the first option value from a ransack code. Would you be able to assist me in addressing this concern? Here is the HTML CODE that I am working with: <select id="q_c_0_a_0_name" ...

The positioning of the JQueryUI menu is experiencing some issues

My goal is to dynamically create menus using JQueryUI menu widgets. Check out this Plunker Example for Dynamic Menu Creation with some issues I am facing an issue where the menu is not positioning itself correctly. It always appears near the bottom of my ...

Attempting to retrieve key-value pairs from a nested JSON array

I am attempting to extract values along with their corresponding key names from a nested JSON array resData =[ { _index: 'web', _type: 'event', _id: 'web+0+93', _score: null, _source: { 'os-nam ...

Managing an undetermined quantity of elements from a form in PHP

Currently developing an inventory page for my job. I've crafted a page that will iterate through my database and showcase all the items stored within. include 'auth.php'; //authentication required for login change $sql="SELECT * FROM `inven ...

Real-time messaging system with php, javascript, and mysql integration for live updates

Hey everyone, I'm in the process of incorporating a Facebook-like messaging system into my web application. Unfortunately, I can't share the link at this time due to login restrictions. In order to achieve this, I have set up a conversation tabl ...

The Drop Down Menu feature in Bootstrap is malfunctioning within the context of a NextJS project

I've built a NEXT.JS application using VS Code. The issue I'm facing is with the drop down menu in the navigation bar - it's not sliding down to display the menu when clicked. Here is the code I'm working with: const loggedRouter = () ...

Utilizing jQuery to manage asynchronous tasks, such as executing AJAX requests, handling promises, and using deferred

Exploring My jQuery Plugins: (function ($, window, document, undefined) { $.fn.loadPageContent = function (url, dataToSend) { url = url || window.location.href; dataToSend = dataToSend ? dataToSend : {}; return $.post(url, data ...

The ng-html-to-pdf-save feature does not function properly when using Persian or Arabic characters

I am trying to utilize this module to print Persian content, but unfortunately, the characters are not displaying correctly. Here is the code snippet I am using: <script type="text/ng-template" id="patient_modal.html"> <div class="modal-heade ...

Using a lone instance of a howler player within a React/NextJS application

I am facing a challenge in my NextJS app where I have multiple audios playing on each page. When a user clicks on an audio button, I want all other audios to stop playing so that only one audio is playing at a time. How can I accomplish this using Howler? ...

What is the best way to generate a div with a dynamically changing variable as its ID?

Creating a quiz where the user can choose how many questions to answer. A function is used to generate individual question divs based on the user's input. Each question displays a Chinese character, and the user must select the correct translation. ...

How can I show a tooltip in vuetify when a button is disabled?

I am currently using the button and tooltip components in my Vuetify project. I am trying to find a way to only display the tooltip when the button is disabled, but I'm having trouble figuring out how to do it correctly. Right now, the tooltip only a ...

How can we optimize ternary statements within ternary statements in Type Script and React Native for best practices?

Can you help me optimize this code snippet that uses nested ternary operators for better readability and correctness? <TouchableOpacity style={ darkMode ? filterState === 'A' ? styles.activeButtonDark : styles.buttonDa ...

Perform a mongoDB query that filters out the data logged in the last 24 hours and groups it by ID along with a count

My current task involves filtering only the logs from the last 24 hours and grouping them by userId to determine how many times each user has logged in. Below is the schema of my MongoDB collection: Key Type timestamp(ISODate) Date ... ... tra ...

The impact of returning 0, 1, or -1 on the outcome of array_udiff_assoc() is crucial in determining the end results

I have a good grasp of what it is and what it does, but I'm struggling to understand how it actually functions, especially with the spaceship operator "<=>". Currently, I am in the process of developing some features for spatie/laravel-activity ...