Steps to generate a nested array of objects within a given array using JavaScript

I currently have an array called ExampleArray which contains different objects with properties like "No", "Name", and "subject". I want to transform this array into a new format where the "subject" property is an array of strings instead.

var ExampleArray=[];  //example array Name
ExampleArray.push ({
    "No": 1,
    "Name": "BB",
    "subject": "NS"
},{
    "No": 1,
    "Name": "BB",
    "subject": "PS"
},{
    "No": 1,
    "Name": "BB",
    "subject": "KS"
}

The desired output would be:

var array = {
    "No": 1,
    "Name": "BB",
    "subject":
    {
        ["NS","SS","KS"]
    }
}

What is the best way to achieve this transformation?

Answer №1

Was my interpretation correct?

let firstElement = ExampleArray[0];

firstElement.subject = ExampleArray.map(item=>item.subject);

Answer №2

Start by creating a fresh object using the method Object#assign, then combine one of the objects from the array with a new object that includes a subjects array generated through Array#map.

Important to note: The utilization of Object#assign results in the creation of a new object without altering the original ones.

var SampleArray = [{ "ID": 1, "Name": "AA", "subject": "MS" },{ "ID": 1, "Name": "AA", "subject": "PS" },{ "ID": 1, "Name": "AA", "subject": "ES" }];

var newObj = Object.assign({}, SampleArray[0], {
  subject: SampleArray.map(function(item) {
    return item.subject;
  })
});

console.log(newObj);

Answer №3

Only under these specific circumstances should you proceed in the following manner:

let info = [{     "No": 1,
                "Name": "DD",
             "subject": "OS"},
            {     "No": 1,
                "Name": "DD",
             "subject": "FS"},
            {     "No": 1,
                "Name": "DD",
             "subject": "AS"
            }
           ],
  finalResult = info.reduce((prev, curr) => Object.assign(curr, (prev.subject = prev.subject.concat(curr.subject), prev)), {subject:[]});
console.log(finalResult);

Answer №4

How to use a for loop in JavaScript

// Create an empty array called ExampleArray
var ExampleArray = [];
// Add objects with keys "No", "Name", and "subject" to ExampleArray
ExampleArray.push ({"No": 1,"Name": "BB","subject": "NS"},{"No": 1,"Name": "BB","subject": "PS"},{"No": 1,"Name": "BB","subject":"KS"});
// Create another empty array called array_subject
var array_subject = [];
// Iterate over each object in ExampleArray using a for loop
for(var i in ExampleArray)
    // Push the value of subject from each object into array_subject
    array_subject.push(ExampleArray[i].subject);
// Set the subject property in the first object of ExampleArray to be array_subject
ExampleArray[0].subject = array_subject;
// Store the modified object in result
var result = ExampleArray[0];
// Log the result to the console
console.log(result);

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 could be the reason behind the failure of this :after element?

I am facing an issue with the preloader on my webpage where the animation is not displaying as expected. The animation should appear on top of a dark black background before the page fully loads, but it seems to be missing. The CSS for the animation works ...

AngularJS Filter from "start to finish" in values

I have been searching everywhere for a solution to this problem, but haven't found one yet. Any help would be greatly appreciated. Angular: var app = angular.module('app', []); app.controller('theController', ['$scope', ...

Troubleshooting Problem with Angular JS Page Loading on Internet Explorer 9

My angularjs single page application is encountering issues specifically in IE9, despite functioning perfectly in Chrome and Firefox. The initial load involves downloading a substantial amount of data and managing numerous dependencies through requireJS. ...

How to retrieve the output of a nested function in Node.js

I have been attempting to retrieve a value from a function nested inside another function in my Node.js application, but it always seems to return undefined. var geo = { list: function(callback){ var returnval; gapi.getcodes(function(e ...

Insert HTML elements into nested CSS classes

My goal is to utilize jQuery for looping through classes and adding text to an HTML element. I am currently working with the following example HTML: <div class="question"> <div class="title"> <strong>Here's the question ...

Is there a way to access the Express parameters within my React component?

Currently, I am in the process of developing a React application that utilizes Express as its back-end infrastructure My express route is configured as follows app.get('/manage/:id', (req, res) => { // redirect to react application }); ...

Dynamic Data Visualization using ChartJS with MySQL and PHP

I'm trying to create a line chart using chartJs that will display MySQL data. Specifically, I would like to use PHP to push the MySQL data to the chartJs. Here is an example of the MySQL table: id | page_views | visitors | month | ---------------- ...

Inquiry into AngularJS data binding

Just dipping my toes into the world of Angular today. Found a tutorial at Angular JS in 30 mins This little project involves setting up basic databinding in Angular. The code features an input box that updates with whatever is typed next to it. As someone ...

Is there a way to retrieve the current map center coordinates using the getCenter function in @react-google-maps/api?

I am currently working with the GoogleMap component provided by @react-google-maps/api, but I am struggling to figure out how to obtain the latitude and longitude coordinates of the map's center after it has been moved. After some research, I came ac ...

Endless AngularJS loop using ng-view

I recently started experimenting with AngularJS for a new project I am working on, but I have encountered a problem when dealing with routes and views. For the sake of simplicity, I have minimized this example to its basic form, yet the issue persists. Th ...

Steps to activate an event when Windows is loaded

Every time windows load, I want to run $('select[name="order_id"]').change(), but it's not working as expected. After debugging in the browser console, I can see that the script $('select[name="order_id"]').cha ...

What is stopping me from injecting an Angular controller?

After some consideration, I made the decision to alter the way in which I inject my controller. I successfully utilized the "$inject Annotation" method, following the instructions provided here. NetworkInterfaceDetailedViewController.$inject['$scope& ...

I am interested in monitoring for any alterations to the @input Object

I've been attempting to detect any changes on the 'draft' Object within the parent component, however ngOnChange() does not seem to be triggering. I have included my code below, but it doesn't even reach the debugger: @Input() draft: ...

Inserting POST request data into subdocument arrays of a database

I am struggling to add data to a nested mongoose sub-document when creating a new schema from the client side. Only the data that is not nested inside another schema/array is being sent over to the database. My database setup includes MongoDB with Mongoos ...

What are alternative methods for Controller communication besides Broadcast/Emit?

I'm having trouble figuring out how to establish communication between controllers in Angular without relying on broadcast/emit methods. Let's consider the scenario where we have Controller1 defined as follows: $scope.calledOnClick = function() ...

Creating manageable CSS styles for a wide variety of themes

I need to add themes to a web application that allows users to switch between them seamlessly. The designers want a variety of font colors and background colors, around 20 in total. Is there a way to achieve this without creating multiple .css files, which ...

Obtain the key by using the JSON value

I am seeking to identify the recursive keys within a JSON Object. For instance, consider the following JSON Object: { "Division1" : { "checked": true, "level": 1, "District1-1": { "checked": true, "level ...

Remove the model from operation

I'm fairly new to angularjs and have a working service. However, I want to move the patient model out of the service and into a separate javascript file. I believe I need to use a factory or service for this task, but I'm not entirely sure how to ...

Using an element with the href property in conjunction with react-router: a comprehensive guide

My goal is to implement the navigation.push(url) functionality upon clicking an anchor tag element in order to prevent the app from refreshing when navigating to a new page, thus allowing me to maintain the application state. The decision to use this on a ...

"Utilizing Bootstrap Modal for efficient AJAX saving of multiple records with the help of bootstrapValidator

I'm encountering an issue with a bootstrap modal form and validation using bootstrapValidator. The problem I'm facing is that when I open the modal, fill out the fields, close it, reopen it, refill the fields, and submit the form, my script inser ...