Traverse through an array of objects with unspecified length and undefined key names

Consider the following object arrays:

1. [{id:'1', code:'somecode', desc:'this is the description'}, {...}, {...}]

2. [{fname:'name', lname:'last name', address:'my address', email:'<a href="/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="7d10043d18101c1411531e1210">[email protected]</a>'}, {...}, {...}]

The goal is to create a function that takes an array and maps their object keys to generic keys like this:

1. [{key1:'1', key2:'somecode', key3:'this is the description'}, {...}, {...}]

2. [{key1:'name', key2:'last name', key3:'my address', key4:'<a href="/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="87eafec7e2eae6eeeba9e4e8ea">[email protected]</a>'}, {...}, {...}]

Initially, mapping the keys directly works fine:

let keys: string[] = Object.keys(this.options[0])
this.replacedItems = this.options.map(item => {
  return{
    key1: item[keys[0]],
    key2: item[keys[1]],
    key3: item[keys[2]],
  }
});

However, attempting a dynamic approach with variable object property numbers leads to undefined results:

let keys: string[] = Object.keys(this.options[0])
this.replacedItems = this.options.map(item => {
  let i=0;
  keys.forEach(key=>{
    let newKey = 'key'+i;
    i++
    return { newKey: item[key] }
  });
}); 

This setup returns an array of undefined values. What could be causing this issue?

Answer №1

To access the current index being iterated over in a `.map` function, use the second parameter and append it to 'key'. Instead of using `Object.keys`, you can opt for `Object.values` to directly retrieve the values without needing the original keys:

const options = [{id:'1', code:'somecode', desc:'this is the description'}];
const replacedItems = options.map(obj => Object.fromEntries(
  Object.values(obj).map((val, i) => ['key' + (i + 1), val])
));
console.log(replacedItems);

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

Trouble with closing Bootstrap 4 modal

My Bootstrap 4 modal is causing issues as it pops up on button click but won't close unless I refresh the page. I've been attempting to get it to close by clicking the 'close' button or simply by clicking anywhere on the main page body. ...

Improprove the design of the dropdown component using React

One of the challenges I am facing in my project is using multiple dropdowns from semantic-ui-react. Each dropdown needs to have different props, making the code look like this: <div className="wrapper"> <img className="icon" src={iconA} ...

Steps for inserting a JSON Array into a database

I have a dropdown menu that displays different options based on the selection from another dropdown. The data for each dropdown is fetched from the database and I need to insert the selected values into a new table in the database. All the necessary code ...

Ways to retrieve the ID of the clicked element from the child up to the parent

I currently have a Parent component and a Child component. The Child component contains inner elements called notes, with "delete" being one of them. My goal is to have the Child component return an ID to the Parent component when the delete element is cl ...

Creating a JavaScript array filled with database data using PHP

Below is a snippet of PHP code used to establish a connection to a database: <?php $host = "localhost"; $user = "admin"; $password = ""; $dbname = "test"; $con = new mysqli($host, $user, $password, $dbname) or die ('Could not connect to the d ...

Is there a way to assign multiple paths to a single page within the NextJS pages directory?

I'm currently working on a project that has two different themes, and I have the ability to switch between them based on the environment. Everything works perfectly, but I'm encountering an issue with paths. Some pages should open with different ...

Stop the HTML5 video playback within a slider (flickity)

As I add slides to a slider using flickity, I am encountering an issue where the first video pauses when there is a slide change event. However, if I play the video on the next slide and then move back or forward, the video does not pause. This is my curr ...

Ways to incorporate type into an object comprised of n element in Typescript

Is there a way to assign types to objects with different keys and values, but where "other" remains constant across all of them? How can this be achieved using TypeScript? { color: "red", size: "small", other: { price: 345 discount: 10 ...

Utilize VBA to iterate through columns in a table and merge the data on a fresh worksheet

Currently, I have 2 tables located on separate tabs, each with a number of columns that share the same names. Ideally, I would like to merge the data from these 2 tables into a new table on a 3rd tab. My attempts so far have involved experimenting with di ...

Prevent right-clicking on links from a particular domain

Looking to prevent right-clicking on a link? Check out this code snippet: <script type="text/javascript" language="javascript> $(document).ready(function() { $('body').on('contextmenu', 'a', function(e){ ...

Building Dynamic Props in Vue.js using v-select Component

I am utilizing a chart that relies on properties for data. <template> <v-row> <v-col col="12" sm="12"> <Chart :data="series2"></Chart> ### This chart receives the props < ...

React native and redux: Updating state with setState is not possible during an ongoing state transition

Currently in the process of developing an app utilizing React Native and redux, alongside Express js for handling Ajax requests. Encountering an issue where the data from my Ajax request fails to load, accompanied by the following warning: Warning: set ...

What is the process for linking my component to my socket.io server?

I am facing a challenge in setting up a socket.io server to facilitate communication between two components: a command interface for sending data, and an overlay component for receiving it. Below is the code snippet: interface.component.html : <input ...

Setting up Electron with React and TypeScript: A Comprehensive Guide

I've been developing an app using Electron, React (jsx), and Babel. However, I recently made the switch to TypeScript and I'm struggling to get everything functioning properly. The npm packages I've tried only work for either React or TypeSc ...

What is the reason for $http.get not requiring a return value?

I am currently developing an angular application and I have a controller that interacts with a service. The controller sends a URL to the service, which then makes a GET request to that URL and receives JSON data in return. Within this JSON data is a URI f ...

The <script> element failed to close correctly

Within my default.jspx file, which serves as the foundational layout for the page, I am attempting to import several jQuery libraries. The code snippet looks like this: <head> ... <spring:url value="/resources/js/lib/jquery-1.9.1.min.js" ...

"Is it possible to rearrange the parent div's position when hovering over a child image with jquery sortable

Can you assist me with a task? I have two text boxes with an equal sign image, and I want the user to be able to move the div only when hovering over the equal sign. This means that the user should be able to drag the div using the equal sign. Can you hel ...

Encountering the error "Error: Maximum update depth exceeded" while coding a React private Route with infinite

Attempting to render components inside private routes only if the user is authenticated, but encountering an error message that reads: "Error: Maximum update depth exceeded." This issue typically arises when a component continuously calls setState within c ...

What could be causing my AngularJS controller to fail in my jasmine test?

I encountered the following error message: "Controller: MainCtrl should retrieve a list of users and assign to scope.users FAILED TypeError: 'undefined' is not a function (evaluating 'Users.findAll()') at /Users/John/NetBea ...

"Steady layout of grid for the navigation bar and

Currently, I am in the process of developing a control panel with the use of HTML and CSS. To structure the page, I opted for a grid layout. However, I encountered an issue where the navbar and sidebar do not stay fixed on the screen despite trying various ...