What is the best way to format and return a result object list in JavaScript or Angular?

I have a question regarding the use of for loops in JavaScript or utilizing Angular to output the resulting object list.

Here is an example of an object list:

var alist = [];
    alist = [
        { 'code': 1000, 'type': 'C', 'a': 4, 'b': null, 'c': null },
        { 'code': 1000, 'type': 'C', 'a': null, 'b': null, 'c': 6 },
        { 'code': 1500, 'type': 'O', 'a': null, 'b': null, 'c': 8 },
        { 'code': 1500, 'type': 'O', 'a': null, 'b': 8, 'c': null },
        { 'code': 1000, 'type': 'O', 'a': 7, 'b': null, 'c': null },
        { 'code': 1000, 'type': 'C', 'a': null, 'b': 7, 'c': null },
        { 'code': 2000, 'type': 'C', 'a': 4, 'b': null, 'c': null },
        { 'code': 2000, 'type': 'C', 'a': null, 'b': 6, 'c': 12 },
        { 'code': 3000, 'type': 'C', 'a': 1, 'b': null, 'c': 12 },
        { 'code': 3000, 'type': 'C', 'a': null, 'b': 6, 'c': null }
    ];

The desired result is to combine objects with the same code and type, while summing up the values of a, b, and c. Here is the expected result:

var resultList = [];
    resultList = [
        { 'code': 1000, 'type': 'C', 'a': 4, 'b': 7, 'c': 6 },
        { 'code': 1500, 'type': 'O', 'a': null, 'b': 8, 'c': 8 },
        { 'code': 1000, 'type': 'O', 'a': 7, 'b': null, 'c': null },
        { 'code': 2000, 'type': 'C', 'a': 4, 'b': 6, 'c': 12 },
        { 'code': 3000, 'type': 'C', 'a': 1, 'b': 6, 'c': 12 },
    ];

Key points to consider:

  1. The 'code' value is dynamic and should not be hardcoded (e.g., 1000, 1500, 2000).
  2. Each unique 'code' only contains one type, such as code 1000 only having type C.

Is it possible to achieve this desired output?

I have attempted to work on this in this jsfiddle, but I have yet to successfully produce the 'resultList'.

Answer №1

To enhance the organization of data, consider utilizing auxiliary arrays for key and parameters collection along with an object for grouping.

var data = [{ code: 1000, type: 'C', a: 4, b: null, c: null }, { code: 1000, type: 'C', a: null, b: null, c: 6 }, { code: 1500, 'type': 'O', a: null, b: null, c: 8 }, { code: 1500, type: 'O', a: null, b: 8, c: null }, { code: 1000, type: 'O', a: 7, b: null, c: null }, { code: 1000, type: 'C', a: null, b: 7, c: null }, { code: 2000, 'type': 'C', a: 4, b: null, c: null }, { code: 2000, type: 'C', a: null, b: 6, c: 12 }, { code: 3000, type: 'C', a: 1, b: null, c: 12 }, { 'code': 3000, type: 'C', a: null, b: 6, c: null }], keys = ['code', 'type'], values = ['a', 'b', 'c'], grouped = [];

data.forEach(function (a) {
    var key = keys.map(function (k) { return a[k]; }).join('|');
    if (!this[key]) {
        this[key] = {};
        keys.forEach(function (k) { this[k] = a[k]; }, this[key]);
        values.forEach(function (k) { this[k] = null; }, this[key]);
        grouped.push(this[key]);
    }
    values.forEach(function (k) {
        if (a[k] !== null) {
            this[k] = (this[k] || 0) + a[k];
        }
    }, this[key]);
}, Object.create(null));

console.log(grouped);
.as-console-wrapper { max-height: 100% !important; top: 0; }

Answer №2

When looking to manipulate your data using pure javascript, the reduce() method can be quite useful.

var dataList = [
  { 'id': 1, 'name': 'John', 'age': 30, 'city': null },
  { 'id': 2, 'name': 'Jane', 'age': null, 'city': 'New York' },
  { 'id': 3, 'name': 'Doe', 'age': 25, 'city': 'Los Angeles' }
];

var updatedData = {}
var newDataList = dataList.reduce(function(result, item) {
  var key = item.id;
  if (!updatedData[key]) {
    updatedData[key] = item;
    result.push(updatedData[key]);
  } else {
    Object.keys(updatedData[key]).forEach(function(prop) {
      if (updatedData[key][prop] == null) updatedData[key][prop] = item[prop];
    })
  }
  return result;
}, [])

console.log(newDataList)

Answer №3

By utilizing the power of lodash, this problem can be elegantly solved:

(function (alist) {
    function mergeObjects(a, b) {
        return _.mergeWith(a, b, function (a, b, key) {
            if (['a', 'b', 'c'].indexOf(key) !== -1) {
                return _.isNull(a) && _.isNull(b) ? null : (a || 0) + (b || 0);
            }
        });
    }

    var result = _.reduce(_.groupBy(alist, 'code'), function (memo, groupedByCode) {
        return _.concat(memo, _.map(_.groupBy(groupedByCode, 'type'), function (groupedByType) {
            return _.reduce(_.tail(groupedByType), mergeObjects, _.head(groupedByType));
        }));
    }, []);

    console.log(result);
})([
    {'code': 1000, 'type': 'C', 'a': 4, 'b': null, 'c': null},
    {'code': 1000, 'type': 'C', 'a': null, 'b': null, 'c': 6},
    {'code': 1500, 'type': 'O', 'a': null, 'b': null, 'c': 8},
    {'code': 1500, 'type': 'O', 'a': null, 'b': 8, 'c': null},
    {'code': 1000, 'type': 'O', 'a': 7, 'b': null, 'c': null},
    {'code': 1000, 'type': 'C', 'a': null, 'b': 7, 'c': null},
    {'code': 2000, 'type': 'C', 'a': 4, 'b': null, 'c': null},
    {'code': 2000, 'type': 'C', 'a': null, 'b': 6, 'c': 12},
    {'code': 3000, 'type': 'C', 'a': 1, 'b': null, 'c': 12},
    {'code': 3000, 'type': 'C', 'a': null, 'b': 6, 'c': null}
]);
  1. Firstly, group by code.
  2. Next, for each code, group by type.
  3. Lastly, for each type, merge the objects while adjusting the values accordingly.

Although this approach may not be the fastest, its declarative nature provides a clear insight into the process. Lodash proves to be an excellent tool for such tasks, and I highly recommend it. Feel free to check out the demo on JSFiddle. Hope this explanation helps!

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

I'm trying to set it up so that an image pops up when I hover over text. I've tried incorporating a few different JavaScripts, but I still can

I'm struggling to display an image on my website. I have the necessary code parts, but it's not working as expected. function showImage() { $('.img').addClass('display'); } function hideImage() { $('.img'). ...

Color change is only visible after adjusting the position, size, or shape of the object

I am facing an issue with changing the color and font of text using fabric js. The problem is that the color change only takes effect after manipulating the object's dimensions. How can I make the color update immediately? Below is my HTML code: < ...

The form does not display the radio button value upon submission

Using redux form for the form elements, I encountered an issue where the radio button values were not being displayed when submitting the form. Despite getting values for email and password fields, the role value from the radio buttons was missing. In my i ...

Retrieve all entries and merge a field with aggregated information in Mongoose (MongoDB)

I am faced with the challenge of working with two Mongo collections, Users and Activities. The Activities collection consists of fields such as createdAt (type Date), hoursWorked (type Number), and a reference to the user through the user field. On the oth ...

Error: The property 'combine' of 'winston_1.default.format' cannot be destructured since it is not defined

Encountered an error while using Winston in Node.js, how can we resolve it? The version of Winston I am using is 3.3.3 and winston-daily-rotate-file version is 4.5.0 I attempted npm i winston@next --save, but the error persists. ** Here is the Error Mes ...

Design an interactive quarter-circle using CSS styling

My goal is to create this element using CSS, however, the content inside needs to be dynamic. I initially attempted to use border-radius, but realized it is unable to achieve the desired outcome. If anyone has a solution or can offer assistance, I would g ...

The date time chart in high charts is not displaying the X-Axis width correctly

Currently, I am utilizing the high charts library to display a date-time column chart. However, there seems to be an issue with the x-axis not displaying the exact starting value for the chart. In the example provided below, it is necessary to adjust the b ...

Issue: Unhandled ReferenceError - onChangeAssignedGroup function is not declared within scope at HTMLSelectElement.onchange

Having difficulty calling a PHP script via JavaScript when the user changes the value in the "Assigned To Group" selection. The goal is to modify the option list of a yet-to-be-created "Assign to User" selection. An error message pops up stating that it d ...

Use JQuery to gradually decrease the opacity of divs individually

I am currently working on a function that fades out all divs except the one that has been clicked on simultaneously. However, I want them to fade out one by one instead. Additionally, I would like the divs to fade out in a random order. If anyone knows ho ...

Choose an option removed upon clicking

I need to remove the option with a value of 0 when the user selects from the dropdown list. Choose: <%@ taglib prefix="form" uri="http://www.springframework.org/tags/form"%> <form:select id="CONTEXTE" path="CONTEXTE" onclick="go()" class="s ...

Exploring shader file content within three.js with the help of jQuery

I am trying to retrieve the content of a string that I have imported using HTML from within another script. To include the text file in question in the html file: <script src="shaders/fragmentshader.fs" id=fragmentshader></script> After impo ...

Having trouble with SCSS styles not being applied after refactoring to SCSS modules?

Currently, I am in the process of restructuring an application to ensure that component styles are separated from global styles using CSS modules. However, I have come across an issue where the styles are not being applied correctly. The original code sni ...

Send an unchangeable list to a component that needs an Array

Just diving into the world of React and learning that using .toJS() is not recommended due to its impact on performance. The dilemma I'm facing is that a third-party component I'm using requires an array as props, while my state is stored as an ...

Utilizing Node.js, delete the author from the database and then use a GET request to display all

Exploring node and express for the first time. I've been working on an example that utilizes GET and POST methods, but now I want to implement DELETE function to delete a book based on its title. Additionally, I need to introduce another GET method to ...

The Javascript regex allows for the presence of positive and negative numbers, with the option of a single minus symbol

oninput="this.value = this.value.replace(/[^-0-9.]/g, '') This code snippet is utilized in my current project. However, there seems to be an issue where the input can contain more than one minus sign, as shown here: ---23 To address this p ...

Discover the nodes with the highest connections in a D3 Force Graph

As I explore the functionalities of a D3 Force Directed Graph with zoom and pan features, I encounter an issue due to my limited knowledge of d3.js. Is there a way to estimate the number of links for each node in this scenario? I am currently at a loss on ...

Mapping memory for FirefoxOS is like equivalent strides

Is there a way to create a memory mapped file in FirefoxOS, Tizen or other pure-JS mobile solutions? In the scenario of a mobile browser where you have large amounts of data that can't fit in RAM or you prefer not to load it all at once to conserve R ...

Instructions on how to insert a single parenthesis into a string using Angular or another JavaScript function

Currently, I am employing Angular JS to handle the creation of a series of SQL test scripts. A JSON file holds various test scenarios, each scenario encompassing a set of projects to be tested: $scope.tests = [ { "Date": "12/31/2017", "Project": ...

The form is failing to redirect to another page

retrieveStudents.js $("#submit").click(function(){ $.ajax({ url: "fetchStudents.php?branchCode=1", datatype:"JSON", success: function(obj){ $("table").append("<form method='POST' action='recordAttendance.php'> ...

Having trouble retrieving properties from a JavaScript JSON object?

I am currently working with a JSON object that contains properties for MAKEs, MODELs, YEARs, STATEs, PLATEs, and COLORs. There are 4 instances of each property within the object: Object {MAKE1="xxx ", MODEL1='xxx', YEAR1='xxx', STATE1= ...