Convert a single array into an array of objects, with keys derived from a JSON response in JavaScript

After making an API call, I am capturing a json response. My goal is to extract the keys and generate an array of objects dynamically, regardless of the number of keys in the response.

To get the keys, I have implemented the following function:

const json_getAllKeys = data => {
   const keys = data.reduce((keys, obj) => (
      keys.concat(Object.keys(obj).filter(key => (
        keys.indexOf(key) === -1))
      )
    ), [])
    return keys 
}

Running this function on a sample json returns an array containing the keys:

['name','username', 'email']

Now, I want to utilize this array to create objects that resemble the following structure:

[
    {
      name: "name",
      username: "username",
      email: "Email",
    }
];

My attempt at mapping the array resulted in multiple objects due to the loop repetition, which isn't desirable for my intended outcome.

keys.map(i=>({i:i}))

[
  { i: 'id' },
  { i: 'name' },
  { i: 'username' },
  { i: 'email' }
]

If you have any suggestions or tips on how to achieve a single object from this array, please share!

Thank you for your assistance! :D

Answer №1

If you're searching for a solution, consider using Object.fromEntries. This feature is part of ECMA2019 and is available in Node versions >= 14. If needed, it can also be provided as a polyfill when utilizing babel.

It's a bit unclear what the expected output of your reduce function should be, but based on the sample input, one approach could be:

const input = ['name','username', 'email'];

const result = Object.fromEntries(input.map(name => ([name, name])));
// result == { name: 'name', username: 'username', email: 'email' }

Answer №2

It looks like you're making progress in the right direction. Remember, the map function will always return an output equal to the input. So if you have an array of 3 elements, you'll get back an array of 3 items.

While using map alone may not achieve your desired outcome, you can consider combining it with reduce. Alternatively, here is a solution using forEach. It may not follow strict functional programming principles, but it gets the job done and could be suitable depending on the context.

let keys = ['name', 'username', 'email']; //defined array
const obj = {}; //initialize empty object
keys.forEach(key => {
    obj[key] = key; //assign values to object properties
})

console.log(obj); //display the modified object
// { name: 'name', username: 'username', email: 'email' }

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

Inserting variables into Angular queries

I am encountering a dilemma on how to insert a variable from an array into a query string. The filter function is functioning properly, but the search function seems to be ineffective. The variable 'id' successfully retrieves the id from the sele ...

Jasmine spies call through problem detected

I can't seem to get my code to work properly and I keep encountering this error: TypeError: undefined is not an object (evaluating 'GitUser.GetGitUser('test').then') ... Check out the code snippets below: app.controller(&apo ...

Tips for retrieving the selected item from Material-UI DropDownMenu

Hello fellow StackOverFlow users, I am new here so please be patient with me In my React app, I am using Material-UI's DropDownMenu to collect information from users. However, the issue I'm facing is that the value being pushed to state is an in ...

Arranging data in ANSI format from an array into a list using C#

I'm struggling with a data sorting problem and need some help. I have a list of values in an array that contain ANSI formatting from a terminal screen, and I want to reconstruct them into a readable list for our test logs. The values look like this: ...

Send information using either ajax or ajax(json) to interact with PHP on the same webpage

I am currently working on a messaging application. My main objective is to retrieve the sender ID and receiver ID by clicking on a single button. Once I have these IDs, I want to send them using AJAX or AJAX(JSON) to PHP within the same page. In PHP, I wi ...

The TypeScript error states that the argument type 'string | undefined' cannot be assigned to the parameter type 'string'

Receiving TS error that says "Object is undefined" I am attempting to retrieve the "userid" from my headers. However, I keep encountering the error message "Argument of type 'string | undefined' is not assignable to parameter of type 'str ...

Angular's GET request response is returning an "Undefined" value instead of the

As an Angular beginner, I've successfully set up and tested a service that retrieves data from a JSON file using the Get method. However, when attempting to access the data inside the JSON file, it returns as undefined. My goal is to use this data as ...

Accessing Firebase data using randomly generated keys

I need to extract the values associated with each key from my JSON file named cardInfo. "cardInfo" : { "-KF3fzOc3e68jRpCkLRb" : 6869098993309203, "-KF3g0fQUJHcexwAFzxz" : 6764366404306628, "-KF3hHOdj-siBxLMNgLa" : 4368998299921 ...

Having trouble retrieving data from an external nested JSON file using jQuery

I'm attempting to retrieve data from an external nested JSON file using AJAX. Here is my AJAX call: <script> var json1 = (function () { var json1 = null; $.ajax({ 'async': false, 'global': false, 'url&a ...

What strategies can I use to optimize the code for the function provided?

This function allows for the dynamic display of select tags for location selection based on employee designation. The current code functions correctly, but I believe it can be optimized further. // Function to activate different location options based on e ...

Combining arrays of varying sizes into one unified array

I have a collection of 100 arrays, each with dimensions of nx1. The value of `n` differs from one array to the next (e.g., `n1 = 50`, `n2 = 52`, `n3 = 48`, etc.). I am looking to combine all these arrays into a single array with the dimensions of `100 x m` ...

Troublesome issue with the Focus() function in JavaScript

I'm having trouble setting the focus on a textbox with the id "txtCity." document.getElementById("txtCity").focus(); Any suggestions on how to make it work? ...

Switching the input type from file to text

My request is to have a file input type that is initially set as read-only, yet still allows the user to manually enter the file name in a text box. Is there a way to achieve this? I want to be able to write the file name similarly to how I would input t ...

Changing the rotation of an object in THREE.js to match Canvas rotation

Hello amazing minds of stackoverflow. I am in the process of converting three js mesh positions to html5 canvas positions. While I have successfully converted vector3 position to canvas position, I am facing difficulties with converting mesh rotation to ca ...

Implementing Conditional ng-src Loading based on a Given Value

I have a dropdown menu that contains a list of image names. When an image is selected, it should be loaded and displayed using the ng-src directive. Everything works perfectly fine when a name is chosen. The issue arises when the dropdown menu also includ ...

What is the best way to retrieve information from both states and dictionaries simultaneously?

I have successfully obtained information from a json file for a specific state and district. However, I am now wondering how to retrieve data for all states and districts? Below is the code I have been using: def get_all_district_data(today): data = ...

How can I efficiently create a suffix using this JavaScript code?

Take note that the code displayed below showcases the array in the console, rather than in the snippet output var names = ["maria", "mary", "marks", "michael"]; function add_suffix(names) { var suffixes = []; for (var i = 0; i < names.length; i+ ...

Steps to trigger a dialog to appear automatically within an Icon Menu with React Material UI

In my application, I have an icon menu implemented along with an array that contains the possible values for the items in the menu. Here is an example of how the array looks: listItems = { [ { label: 'ZERO', t ...

Error: 'window not defined' or 'document not defined' encountered while importing a module in Next.js

I'm working on integrating a Wysiwyg editor into my web application. However, I encountered an error when trying to import the editor module. I tried using both react-draft-wysiwyg and react-quill. The former resulted in a "window not defined" error, ...

Using Omit<T,K> with enums does not yield the expected result in Typescript

The setup includes an enum and interface as shown below: enum MyEnum { ALL, OTHER } interface Props { sources: Omit<MyEnum, MyEnum.ALL> } const test: Props = { sources: MyEnum.ALL } // triggering a complaint intentionally I am perplexed b ...