The task of mapping an array of objects with nested values using JavaScript is proving to

Attempting to convert an array of objects with nested values in child objects like:

const objs = [{
        "B": {
            "value": 1,
        },
        "D": {
            "value": "45"
        },
        "E": {
            "value": "234"
        },
        "A": {
            "value": "543"
        },
        "C": {
            "value": "250"
        }
    },...]

into a new structure as shown below:

[
  { name: 'B', value: 1 }, 
  { name: 'D', value: '45' }, 
  { name: 'E', value: '234' }, 
  { name: 'A', value: '543' },
  { name: 'C', value: '250' }
]

however, the result of the mapping is undefined

const mapped = objs.map((key, index) => {
  Object.keys(key).map(el => ({
    name: el
  }))
})

For more details and examples, check out this Stackblitz link

Answer №1

Please don't forget to include the return statement and define the value property.

Additionally, you might consider using flatMap over map to prevent a nested array in the output:

const objs = [{
    "B": {
        "value": 1,
    },
    "D": {
        "value": "45"
    },
    "E": {
        "value": "234"
    },
    "A": {
        "value": "543"
    },
    "C": {
        "value": "250"
    }
}]

const mapped = objs.flatMap((key, index) => {
    return Object.keys(key).map(el => ({
        name: el,
        value: key[el].value
    }))
})

console.log(mapped)

Answer №2

Working with objs[0] is recommended over working with objs, as the former represents an array containing a single object rather than multiple objects.

let newArray = []
for(let key in objs[0]){
newArray.push({
"name": key,
"value": objs[0][key].value
})
}

Answer №3

The code is missing a return statement in the Object.keys method. Instead of using Object.keys, consider using Object.entries to access both the key and value.

const objs = [{
  "B": {
    "value": 1,
  },
  "D": {
    "value": "45"
  },
  "E": {
    "value": "234"
  },
  "A": {
    "value": "543"
  },
  "C": {
    "value": "250"
  }
}];
const mapped = objs.map((key, _) => {
  return Object.entries(key).map(([name, {
    value
  }]) => ({
    name,
    value
  }))
}).flat();

console.log(mapped);

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

Concerns regarding code coverage when testing asynchronous functions using nockjs and jest

In my latest project, I've created a basic unit test for making API calls using NockJS and Jest within a React application. Here's a snippet of the code: AjaxService.js export const AjaxService = { post: (url, data, headers) => { ...

The userscript will keep the window open as long as it remains inactive

Hello everyone, I'm excited to join the StackOverflow community and dive into userscripts for the first time! Putting aside any unnecessary details, I'm encountering a small issue with a script I recently created. (function () { $("#enbut"). ...

Issue with burger menu functionality, button unresponsive

Two files are involved in this issue, one is a Vue file and the other is a JavaScript file. The JavaScript file contains an array and the problem is being described in the console. Additionally, there may be an issue with items as sometimes the same error ...

The initial value in useEffect is not being updated by useState

I am currently implementing a like feature for my web application. The issue lies in the fact that my setLike function is not updating the state even after using setLike(!like). I verified this by adding console.log() statements before and after the setLik ...

What is the best way to initiate a TouchEvent in a qunit test being run by grunt using only vanilla JavaScript?

I have implemented callbacks for different touch events that require testing. For example, the 'touchstart' event utilizes touch coordinates to configure a class member: NavigationUI.prototype.touchStart = function(evt) { this.interacting = ...

Tips for assigning unique names to each radio input groupNeed to assign unique names to radio

Currently, I am seeking a dynamic solution to alter the name associated with a set of radio input buttons. The situation involves creating a travel itinerary where users can choose between "domestic" and "international." Based on this selection, the corre ...

The positioning of Material UI InputAdornment icons is located beyond the boundaries of the TextField input area

I am struggling to understand why my InputAdornment is not positioned correctly. There doesn't seem to be any style in my code that would affect the location of the icon within the TextField (such as padding or flex properties). Currently, the calen ...

Generate nth-child selectors in a Material-UI component using props dynamically

I am currently working on customizing the Material UI slider component, specifically focusing on its marks prop to display the number of occurrences for each data object within the marks array. The desired appearance of the slider is illustrated in this i ...

guide for interpreting a complex json structure

I'm attempting to extract data from a JSON file that has multiple layers, like the example below. - "petOwner": { "name":"John", "age":31, "pets":[ { "animal":"dog", "name":"Fido" }, ...

Leverage the version attribute within package.json within one of its scripts

Is there a way to access the version attribute of my package.json file within one of its scripts? I want to include the version number in the name of the JS bundle, instead of using a hash as an identifier. This is what I currently have: "build-js": "bro ...

Issue with jQuery fadeTo() not working after appendTo() function completes

I am facing a problem with the code below that is meant to create a carousel effect for my website. The main issue I am encountering is that the original fadeTo() function does not actually fade the elements, but rather waits for the fade time to finish an ...

Is there a way to work around the CORS policy in order to fetch data from URLs?

I have been developing a tool that can analyze URLs from an uploaded CSV file, search the text content of each URL, and calculate the total word count as well as the occurrences of "saas" or "software". The goal is to generate a new CSV file with the origi ...

Save a newly uploaded image to Github utilizing NodeJS and the Github API

Struggling to upload an image to my Github repo using NodeJS and Github API has been a challenge for me. I have managed to create the SHA, Commit Tree, and all necessary steps, but the final hurdle is passing the image to the API and saving it as an actual ...

Requesting information asynchronously returns a positive response

I wrote the following code: if (venue_exists(instagramUserID)){ alert('A'); }else { alert('C'); } function venue_exists(instagramUserID) { $.get( "/venues/" + instagramUserID, function( ...

Align dropdown navigation menu/sorting dropdown in the same position as the button

Exploring the world of dropdown menus in CSS has led me to encounter some challenges. I am striving to ensure that the dropdown boxes appear on the same line as the button that triggers them. Below is the CSS code I have been working with: /* global style ...

What is the best way to utilize ng-if to conceal a component in AngularJS when a button in a separate component is clicked?

I am facing a challenge with two child components within a parent component. My goal is to hide component1 when a button in component2 is clicked. Below is an illustration of the current code I am handling: Parent Component HTML: <div ng-app='ap ...

Creating JSON arrays with JavaScript and jQuery

User Information var Users=[{"Id":1,"FirstName":"John"},{"Id":2,"FirstName":"Emily"}] Call Information var CallInfo=[{"Id":1,"PercentageCalls":"22 %","TotalTime":"60:24 minutes","PercentageTime":"0 %","AvgTime":"0:22 minutes"},{"Id":2,"PercentageCa ...

What is the best way to handle query string parameters when routing in Next.js?

One of the challenges I am facing is related to a URL structure like this: bar?id=foo When I navigate to this URL using router.push('bar?id=foo'), everything works perfectly. However, if I directly access the route in the browser, the query st ...

Error: The layout was unable to display the template body

I've been working on a web application with express and eta, but I'm running into an issue with including partials in my templates. Despite trying to include a file partial (refer to the Docs), the compiled template doesn't seem to incorpor ...

Encountering an error while attempting to launch an AngularJS application on Node.js? Let's

Currently, I am in the process of learning Angular. Whenever I attempt to run my code, an error message pops up: > <a href="/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="1f7a737a7c6b6d70715f2b312f3115">[email protected]< ...