What is the implementation of ForEach within map in JavaScript?

I am working with a sample JSON in the following format:

   var sample=[{"id":200,"children":[{"value":300,"type":"SINGLE"},{"value":400,"type":"CLASSIC"},{"value":600,"type":"DUAL"}]},{"id":300,"children":[{"value":500,"type":"TRIO"},{"value":600,"type":"MUSICAL"},{"value":700,"type":"UMBRELA"}]}]

var result = [];
sample.forEach(function(e){
  let obj = {}
  obj.id=e.id
  obj['somekey']=e.children[0].value
  obj['someanotherkey']=e.children[1].type
  result.push(obj);
})
console.log(result)

Is there a way to achieve the same result using es-6 map?

Answer №1

let data=[{"id":100,"children":[{"value":200,"type":"SINGLE"},{"value":300,"type":"DOUBLE"},{"value":400,"type":"TRIPLE"}]},{"id":200,"children":[{"value":500,"type":"QUAD"},{"value":600,"type":"QUINTUPLE"},{"value":700,"type":"SEXTUPLE"}]}]
let result = data.map(({ id, children }) => ({ id, ...children[0] }));
console.log(result);

Answer №2

.map() function in JavaScript is used to transform elements of an array and returns a new array. To store the result, you need to assign it to a variable. Inside the map function, you can use the return statement to add items to the new array.

var sampleArray = [{"id":200,"children":[{"value":300,"type":"SINGLE"},{"value":400,"type":"CLASSIC"},{"value":600,"type":"DUAL"}]},{"id":300,"children":[{"value":500,"type":"TRIO"},{"value":600,"type":"MUSICAL"},{"value":700,"type":"UMBRELA"}]}];

let resultArray = sampleArray.map(function(element){
  let obj = {}
  obj.id = element.id;
  obj['value'] = element.children[0].value;
  obj['type'] = element.children[0].type;
  return obj;
});

console.log(resultArray);

Answer №3

To have the option to select the index of the children:

const fetchChildData = (arr, index) => arr.map(({id, children: ch}) => ({id, ...ch[index]}));

console.log(fetchChildData(dataSample, 1)); // specify the desired index here

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

Set all form fields to ng-touched programmatically when the form is submitted

HTML: <div class="form-group" ng-class="{ 'has-error' : form.firstName.$invalid && form.firstName.$touched }"> <label for="firstName" class="control-label"> First Name </label> <input t ...

Is there a way to access the route name (path) in Express Node.js while making a request using the req object?

Within my Node.js Express server, I have implemented a generic middleware where I am trying to retrieve the route name. Here is an example: app.use(function (req, res, next) { //using a specific npm package that allows me to execute functions after send ...

Error message: Unable to locate local module in node.js subdirectory

Exploring the folder structure within my application https://i.stack.imgur.com/Pkxpg.png Referring to app_modules/bar and app_modules/foo as local modules Root Folder package.json "dependencies": { "body-parser": "~1.18.2", "cookie-parser": "~ ...

Navigating the update and deletion of master-detail relationships in JSON structures

We are receiving the JSON Data in the following format, $invoice_data = { "CONTACT_ID": "1", "INV_SERIAL_NO": "100", "NAME": "baby", "INV_DATE": "2018-06-27", ...

The toggleCategories function seems to be malfunctioning as it is only showing the sequence number as 0 in ReactJS

I am currently working on a portfolio using the React framework. One of the features I have implemented is a project page where multiple projects are displayed within tabs. However, I am facing some issues with the functionality. toggleCategories(){ ...

Creating sequential hover animations with CSS in HTML

I have a total of four divs that I want to hover continuously, one after the other. Here is the code I am currently using: #rij1 .content-overlayz, #rij1 .content-details { animation-duration: 2s; animation-name: stepped-pulse; animation-iterati ...

Is it feasible to utilize the translate function twice on a single element?

Using Javascript, I successfully translated a circle from the center of the canvas to the upper left. Now, my aim is to create a function that randomly selects coordinates within the canvas and translates the object accordingly. However, I'm encounter ...

Updating reactive form fields with patched observable data in Angular

Struggling with initializing a reactive form in my component's onInit() method, as well as handling data from a service to update or create entries in a MySQL table. The issue lies in using patchValue to pass the retrieved data into the form: compone ...

Show a random number within a Bootstrap tooltip

I am trying to make a bootstrap popover display a random number every time it is clicked, but my current implementation is only showing the initial number generated and does not update on subsequent clicks. Below is my code snippet: <button type=&qu ...

Using Jquery to loop through various select options within a designated container div

I am seeking a way to loop through multiple select options within a specific div using the jQuery each function. If any field is left empty during this iteration, I would like the loop to break and set the reqCourseFlag variable to 0. The current implement ...

Tips for verifying that a file has not been selected in Croppie

Whenever I use croppie to crop images on my website, everything works fine when I select an image and upload it. But if I try to crop and upload without selecting an image, a black image gets uploaded instead. How can I validate if the file upload is empty ...

Toggle the div's visibility to fade in and out once more

Apologies if this is a simple issue to resolve. My goal is to create a div that, when selected, will be replaced by another div with the option to switch back to the original div when "back" is clicked. This is my current progress: $(document).ready( ...

What is the best method to modify the accurate phone number within my script?

I need help with a text format script. link HTML CODE: <label for="primary_phone">Primary Phone Number<span class="star">*</span></label> <br> <input type="text" name="primary_phone" id="primary_phone" class="_phone requ ...

Navigating through hashed URLs with a Flexslider component

I have a website under construction that utilizes a flexslider, and I am looking to incorporate URL hash navigation. My goal is to extract the slide index based on the URL hash. I have examined the code for manual navigation where the index of the clicked ...

Challenges faced when parsing JSON in Lua

I've encountered an issue with the code below: PerformHttpRequest('http://ossie.dk/API/verify.json',function(err, text, headers) local r=json.decode(text) for s,t in pairs(r.servers)do print(t) end end,"GET","",{}) The ...

Storing information in a MongoDB database using Node.js

Context: Looking to insert data into a MongoDB database using Node.js Problem Statement: Attempting to insert data into the MongoDB database but encountering an error. Unable to locate the issue. Present Output: Reference Error Attach Code: filter.js ...

Error in jQuery: Null property causing TypeError when reading 'text'

Issue: I have a modal form that is loaded via an ajax call. Inside the modal, there is a span element containing an email address. I am trying to capture the value of this span element using JavaScript. Currently, I have a button click event that triggers ...

Having trouble getting web components registered when testing Lit Element (lit-element) with @web/test-runner and @open-wc/testing-helpers?

Currently, I am working with Lit Element and Typescript for my project. Here are the dependencies for my tests: "@esm-bundle/chai": "^4.3.4-fix.0", "@open-wc/chai-dom-equals": "^0.12.36", "@open-wc/testing-help ...

Error: The Twitter Search API requires integer values for string indices

I've been experimenting with the Twitter Search API, and I've written some code using the requests module: text part of the JSON data, I used the following code:</p> for tweet in r.json(): print tweet['text'] However, I enc ...

stopPropagation() halts the propagation in the opposite direction

I encountered an issue while attempting to create a non-clickable div. While it does stop propagation, it doesn't prevent what should be stopped and allows things that shouldn't be clickable. js //screen has set stopPropagation $("#smokeScree ...