Developing original data from an array in JavaScript

I am looking to create an API body for use in JavaScript fetch. The array contains around twenty items and I need to iterate through it using a loop.

Here is an example of my array of objects:

[
    {
        name:"x",lname:"y"
    },
    {
        name:"x2",lname:"y2"
    },
]

This is the desired output structure:

{
    "0":{
        "name":"x",
        "lname":"y"
    },
    "1":{
        "name":"x2",
        "lname":"y2"
    },
}

This is how it appears in Postman when sent as the body:

https://i.sstatic.net/k63lI.png

Any suggestions or assistance would be greatly appreciated.

Answer №1

To transform an Array into an Object, you can easily achieve this using the Array.reduce method and assigning the index as the key for each property:

const data = [
    {name:"x",lname:"y"},
    {name:"x2",lname:"y2"},
]

console.log( 
  data.reduce((acc, item, i) => ({...acc, [i]:item}) ,{})
)

Alternatively, you can achieve the same result more succinctly, as suggested by @CherryDT (in the comments below), which automatically converts the Array into an Object where keys are derived from the indices of the array items:

const data = [
    {name:"x",lname:"y"},
    {name:"x2",lname:"y2"},
]

console.log({...data})

Pro Tip: If you prefer the keys of the resulting Object to start from 1 instead of 0, you can do this:

console.log({...[,...data]})

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

What is the best way to eliminate the hash from the URL of a single-route Angular application without the need for ui.router?

I came across a question that has been asked before on Stack Overflow, but unfortunately, it remains unanswered and without any comments. In my Angular app, I am working with a single route and I want to find a way to eliminate the # from the URL. If I h ...

How to display a minimalist white dot in three.js

I am currently working with THREE.WebGLRenderer and I have a requirement to display multiple white dots of the same size at specific locations in 3D space. Is it recommended to use sprites, calculate the 2D screen coordinates, and utilize SpriteMaterial w ...

Is there a way to create a customized calendar in Node.js?

I am looking for a way to showcase a calendar in a localized format, not only in terms of language but also supporting non-Gregorian calendars such as Persian, Chinese, or Buddhist. In the past, when I worked with Java, I relied on ICU4J for this task. Ho ...

Encountering a problem during the conversion of HTML to JSON

I am facing an issue with the content of a specific div on my webpage. <div id="hidLocsJsonForAutoComplete" style="display:none;">[{"id":1,"desc":"Amazon","name":"amazon"},{"id":2,"desc":"Apple Bees","name":"applebees"},{"id":3,"desc":"Babys r Us"," ...

Parcel Bundler works perfectly fine on localhost, however, an error is being displayed on the index.html file in the Dist folder

Currently, I am in the process of learning how to use Parcel for bundling purposes. I have set up a index.html file that is connected with index.js. Surprisingly, everything works perfectly fine when I access it via localhost:1234 using Parcel. However, wh ...

Getting props value in parent component using Vue JS

In my development project, I am working with three key components: component-1, component-2, and an App component. Initially, I pass a Boolean prop from component-1 to component-2. Through the use of a @click event, I am able to toggle this prop value betw ...

Locating the elusive sequence number within a document

Greetings, I am currently trying to locate a missing number within an xml file but seem to be encountering some challenges. Any suggestions or ideas would be greatly appreciated. Example The file contains an <a> tag with various ids such as page-1, ...

Obtaining a Slug in the Server-Side Layout of a Next.js Component

I am facing an issue with passing a slug to a server-side function in my Next.js layout component. The problem arises when the slug is returning as undefined, and I am struggling to correctly access and utilize the slug on the server side within the layout ...

AngularJS can retrieve the selected value from a select tag

<select ng-model="data.person"> <option value="1" selected="">1 pax</option> <option value="2">2 pax</option> </select> The ng-model above returned "1 pax," but how can I retrieve ...

The index declaration file has not been uploaded to NPM

After creating a Typescript package and publishing it on NPM, I encountered an issue with the declaration files not being included in the published version. Despite setting declaration: true in the tsconfig.json, only the JavaScript files were being publis ...

The syntax for importing JSON in JavaScript ES6 is incredibly straightforward and

Whenever I attempt to write my code following the ES6 standard and try to import a .json file, it ends up failing on me. import JsonT from "../../Data/t.json" //not functioning as expected var JsonT = require('../../Data/t.json'); //works fine ...

Why is JavaScript globally modifying the JSON object?

I have a few functions here that utilize the official jQuery Template plugin to insert some JSON data given by our backend developers into the variables topPages and latestPages. However, when I use the insertOrHideList() function followed by the renderLis ...

Creating Scalable Vector Graphics without utilizing identifiers

For instance, if we have defs and rect defined separately, we would typically use an ID. <defs> <linearGradient id="MyGradient"> <stop offset="0%" stop-color="#000" /> <stop offset="100%" stop-color="#fff" /> ...

What is the best way to incorporate a transition effect into a flex item with a specified max-width, where the width adjustments are managed by a child div?

The example below demonstrates a situation where the child's width grows with a smooth transition, but the parent's width abruptly changes! What I aim for is to have both the child's width and the parent's width transition smoothly. I ...

It's impossible to remove a dynamically added class from a button

I'm facing an issue with adding and removing classes from a button using jQuery. I added a new class to the button, then removed it, but now when I click the button again I want to revert back to the initial class. Unfortunately, my code is not workin ...

Testing the update functionality of meta content in the Vue Quasar Meta component using Jest

I am currently working on unit testing the process of updating meta content for a Vue & Quasar page by utilizing the useMeta component offered by Quasar. My approach to testing this involves creating a mock Vue component called UseMetaComponent, which is ...

Explore the associative array within a JSON using jQuery to extract and manipulate the values within the array

I'm working with a JSON file containing surnames and first names in an array, along with other objects. How can I specifically extract the names "Jhon" and "Jason"? Below is a snippet from my JSON file: [{ "surname": "Vlad", "first_name": [ ...

Enhancing React Performance: Storing Component Identity in Redux State

Can I safely pass this to a Redux action creator from a component defined using React.createClass? In my code, I have created the following reducer: const unsavedChangesProtectionReducer = handleActions({ [ENABLE_UNSAVED_CHANGES_PROTECTION]: (unsaved ...

Ways to Determine if a User Has Closed the Page

How can I detect when a user closes the page without using the back button or typing in a different URL in the address bar? I've attempted to use the following code: $(window).bind('beforeunload', function () { logout(); }); This solutio ...

Tips for keeping your button fixed in place

I am encountering an issue where my button moves below the select dropdown list when I try to make a selection. Is there a way to keep the button in place even when the dropdown list from the select box is visible? For reference, here is the current outp ...