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

Exploring the possibilities of combining Selenium Code and F# with Canopy

Currently, I am facing the challenge of incorporating Selenium code into my F# project while utilizing the canopy wrapper. Canopy relies on Selenium for certain functions. My main struggle lies in converting Selenium code from Java or C# to fit within an ...

"Track the progress of a form submission with a loading indicator using Sweet

I am looking to incorporate a waiting time animation when submitting a form, and I prefer using SweetAlert over a traditional loading image. Here is the basic code snippet: $("form").submit(function (e) { e.preventDefault(); // prevents def ...

Guide to simulating Twilio with Jest and TypeScript to perform unit testing

Please assist me in mocking a Twilio service that sends messages using Jest to mock the service. Below is the code I am working with: import { SQSEvent } from "aws-lambda"; import { GetSecretValueResponse } from "aws-sdk/clients/secretsmanag ...

Unable to Retrieve Modified Content with $().text();

In the process of developing an app, I am encountering a challenge where I need to transfer user input to another element after processing it. However, I am facing an issue with accessing the updated value of the <textarea> using .text(), as it only ...

Issue encountered while validating password using regex pattern?

There seems to be an issue with password validation when requiring 1 upper case, 1 lower case, 1 number, and 1 special character. methods: { validateBeforeSubmit() { this.$validator.localize('en', dict) this.$validator.validate ...

Implementing auto-complete functionality using two keys in Material UI and React

My goal is to enable autocomplete for input when searching with values like title and year. Strangely, the autocomplete feature only works when I search with title. Searching with year does not yield any options. Sample code export default function ComboB ...

Modify the label contents to reflect the selected file, rather than using the default text

Currently, I am working on customizing my file upload input to enhance its appearance. Everything is going smoothly so far, but I am facing difficulty in finding a suitable jQuery script that can meet my specific requirements. My objective is to have the ...

How come my form isn't functioning properly on mobile devices?

I recently downloaded a form from the website and integrated it within my desktop site successfully. However, when accessed on mobile devices, specifically iOS, the submit button changes to "sending ..." and the form gets stuck without displaying any erro ...

If a particular <td> element is present on the page, exhibit a unique <div>

I have a webpage with various HTML elements. <div class="alert">Your message was not sent.</div> <p class="pending">Email Pending</p> I would like to display the div.alert only if the p.pending is present. Is ...

Adding a component dynamically with a link click in Angular: A step-by-step guide

I am encountering an issue with my web application setup. I have a navigation bar, a home page with left and right divs, and a view-associates component. My goal is to dynamically add the view-associates component into the home's right div when a spec ...

How can we stop the parent modal from closing if the child component is not valid?

I have a main component with a modal component that takes another component as a parameter. The child modal component has some logic where I need to check if the child component is valid before closing the modal. const MainComponent: FC<IProps> => ...

Improve the parallax effect in your React component

Do you have any tips on smoothing out the scrolling animation for a React component with a simple parallax effect? I tried using requestAnimationFrame() in vanilla JS, but it doesn't seem to work well within the React component's rendering cycle. ...

Syntax in Next.js for shallow routing

When working with next js, I want to update the route without refreshing the page. Currently, I am using the following syntax which I find cumbersome: Router.push( `/statistics?entityId=${id}&type=${entityType}&provider=${serviceProvider}`, ...

Mastering Typecasting in TypeScript: A comprehensive guide

I have a loadMore function that retrieves data and returns a Promise of either Project[] or Folder[] or undefined. const items = await loadMore(); How can I specifically cast the type of 'items' to Folder[] in TypeScript? ...

The user authentication is not recognized in the current session (Node.js, Express, Passport)

I have encountered an issue where req.user is undefined, despite my efforts to troubleshoot for over 4 hours. I even resorted to copying and pasting the server/index.js file from a friend's server, modifying the auth strategy to suit my own, but the p ...

Can data be transferred from one website to another without the use of an API?

I am a newcomer to the world of web development with basic knowledge of JS, Node, Express, Mongoose, and MongoDB. I have an exciting idea for a web application that would function like a spreadsheet, gathering user inputs to generate an output. The unique ...

Steps for creating a Foundation 6 accordion

Can anyone assist me in creating a Foundation 6 accordion? I tried to follow the code from the documentation, but it's quite confusing. I seem to be missing something and can't figure out what. Here is the HTML code from the docs: <ul class= ...

Sending real-time data from the tRPC stream API in OpenAI to the React client

I have been exploring ways to integrate the openai-node package into my Next.js application. Due to the lengthy generation times of OpenAI completions, I am interested in utilizing streaming, which is typically not supported within the package (refer to he ...

Building interactive web forms with real-time validation using CodeIgniter

I'm looking for a way to use ajax (jquery library) to validate my forms. Specifically, I have a form that requires a minimum password length of 6 characters. Currently, I have implemented the validation rule as follows, $this->form_validation-> ...

Error: The options object provided for Dev Middleware initialization does not adhere to the API schema and is considered invalid

Currently delving into the world of React JS, I am still a newcomer when it comes to these technologies. Upon updating webpack from version 4.30.0 to 5.10.0 and running npm start, some errors surfaced. Despite attempting to remove the node_modules directo ...