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

Tips for securely encrypting passwords before adding them to a database:

While working with Nest.Js and TypeORM, I encountered an issue where I wanted to hash my password before saving it to the database. I initially attempted to use the @BeforeInsert() event decorator but ran into a roadblock. After some investigation, I disc ...

Trouble with variable in require path causing issues with r.js

As a newcomer to optimizing with r.js, I am also a big fan of requirejs build-config.js ({ appDir: "./src/main/webapp/webresources/javascript/", baseUrl: "./", dir: "./target/webresources/js", optimizeCss ...

Using JavaScript to retrieve data from a JSON file and showcase it on a jQuery mobile webpage

I am struggling to retrieve JSON data from a PHP URL using JavaScript and display it within a JQuery mobile "li" tag as a category list. Despite spending the last 8 hours on it, I can't seem to get it working using the code provided below. Any help wo ...

How come I am receiving the E11000 error from Mongo when I have not designated any field as unique?

Encountering an issue while attempting to save the second document to MongoDB Atlas. The error message reads as follows: Error:MongoError: E11000 duplicate key error collection: test.orders index: orderId_1 dup key: { orderId: null } Despite having no un ...

ES6 import of CSS file results in string output instead of object

Too long; Didn't read I'm facing an issue where the css file I import into a typescript module resolves to a string instead of an object. Can someone help me understand why this is happening? For Instance // preview.ts import test from './ ...

Detecting changes in a readonly input in Angular 4

Here is a code snippet where I have a readonly input field. I am attempting to change the value of this readonly input from a TypeScript file, however, I am encountering difficulty in detecting any changes from any function. See the example below: <inp ...

The Angular test spy is failing to be invoked

Having trouble setting up my Angular test correctly. The issue seems to be with my spy not functioning as expected. I'm new to Angular and still learning how to write tests. This is for my first Angular app using the latest version of CLI 7.x, which i ...

Is it possible to dynamically retrieve an element's style from @ViewChild in an Angular 2 component without needing an active approach?

For instance, there's an element in the template that uses a local variable #targetElement to retrieve its current width whenever needed. However, I prefer not to calculate the style programmatically. I attempted using a setter with the @ViewChild ann ...

Issue encountered with the openpgpjs example: `'The function openpgp.encrypt is not defined'`

I encountered an issue with the 'openpgp.encrypt is not a function' error while attempting to follow the sample provided on the openpgp.js github page: https://github.com/openpgpjs/openpgpjs/blob/master/README.md#getting-started After following ...

Creating a dynamic search bar with multiple input fields in HTML

My JSON input for typeahead looks like this: [{"q": "#django", "count": 3}, {"q": "#hashtag", "count": 3}, {"q": "#hashtags", "count": 0}, {"q": "#google", "count": 1}] This is the code I have to implement typeahead functionality: var hashTags = new Blo ...

Prevent event propagation in jQuery by using .stopPropagation() when hovering over a

When trying to implement event.stopPropagation() in a specific scenario, I encountered an issue with a blinking background image on my submenu. To address this, I added a pseudo-element (background:green) to the parent element by toggling a new class using ...

Issues with the functionality of the asynchronous socket.io JavaScript callback are being experienced

I am facing an issue with my JavaScript code that involves querying data from a database using Node.js and Socket.io. Currently, I have implemented setTimeout() functions to make it work, but I want to switch to using callbacks for better reliability. Howe ...

Unpacking objects within an array in the backend of a Next.js application

How can I resolve this issue? I am passing the req.query parameter with an array but I am unable to destructure or use items from the array. In my Next.js API backend, I only get [object Object] or undefined. How can I access and select specific values fro ...

Error with Expression Engine: PHP function cannot be executed

I have been attempting to execute a PHP Script with ExpressionEngine tags using Ajax on my webpage. I followed the documentation and set up the PHP script accordingly, but it appears that I am unable to call the function in the PHP script. There must be so ...

What causes the DOM to be updated upon each opening of the browser extension for Chrome?

Here is the default position: https://i.stack.imgur.com/tkWCA.png After checking it: https://i.stack.imgur.com/tdzbg.png When I click anywhere on the page to hide the dom extension output (without showing popup.html); However, when I reopen the extens ...

When nodemon is executed, it encounters an "Error: Cannot find module" issue, indicating that it may be searching in the incorrect directory

I recently encountered an issue with my Node.js project that utilizes nodemon. Despite having the package installed (located in /node_modules), I am experiencing an error when trying to start my Express server with nodemon through a script in my package.js ...

Unlocking the Potential: Employing postMessage in an iFrame to Seamlessly Navigate Users towards an Enriching Destination on

One of my webpages includes an iframe. Here's the challenge: I want a button within the frame to redirect users to another page without reloading the iframe's content. Instead, I want the URL of the main window to change. Unfortunately, I haven& ...

Angular tutorial on splitting a JSON array

I am looking to extract a portion of a JSON array in Angular. The array looks like the one in the image below.https://i.stack.imgur.com/w0hqC.png Below is the code snippet: export class AppComponent { color: string = 'green'; public stocklis ...

Ways to adjust a specific div within an ng repeat using the value from JSON in AngularJS

When I select a different option from the dropdown menu, such as cities or states, the values are populated from a JSON file. My specific requirement is to hide a button only when the value 'No data' is populated upon changing the dropdown select ...

Error: The function `push` cannot be used on the variable `result` (TypeError)

Here is a snippet from my react component const mockFetch = () => Promise.resolve({ json: () => new Promise((resolve) => setTimeout(() => resolve({ student1: { studentName: 'student1' }, student2: { studen ...