Iterate through an array of objects using underscores, make alterations to specific objects, and eliminate other objects

Let's say I have an array of objects:

[{"month":"03-2016","isLate":"N","transactionCount":4,"transactionAmount":8746455},{"month":"05-2016","isLate":"N","transactionCount":5,"transactionAmount":-40004952945.61},{"month":"06-2016","isLate":"N","transactionCount":1,"transactionAmount":100000},{"month":"04-2016","isLate":"N","transactionCount":6,"transactionAmount":-117189.89},{"month":"02-2016","isLate":"N","transactionCount":4,"transactionAmount":-5331000},{"month":"04-2016","isLate":null,"transactionCount":2,"transactionAmount":-4888.89},{"month":"03-2016","isLate":null,"transactionCount":3,"transactionAmount":5000}]

Are there any functions in Underscore or JavaScript that can iterate over each item in the array, remove specific objects based on certain conditions, or modify objects by adding more information before returning the updated data?

Answer №1

If you're working with plain JavaScript, you have the ability to:

  • Remove specific objects using the filter() method
  • Modify objects by adding more information utilizing the map() method

Here is an example:

var input = [
  {
    "month": "03-2016",
    "isLate": "N",
    "transactionCount": 4,
    "transactionAmount": 8746455
  },
  {
    "month": "05-2016",
    "isLate": "N",
    "transactionCount": 5,
    "transactionAmount": -40004952945.61
  },
  {
    "month": "06-2016",
    "isLate": "N",
    "transactionCount": 1,
    "transactionAmount": 100000
  },
  {
    "month": "04-2016",
    "isLate": "N",
    "transactionCount": 6,
    "transactionAmount": -117189.89
  },
  {
    "month": "02-2016",
    "isLate": "N",
    "transactionCount": 4,
    "transactionAmount": -5331000
  },
  {
    "month": "04-2016",
    "isLate": null,
    "transactionCount": 2,
    "transactionAmount": -4888.89
  },
  {
    "month": "03-2016",
    "isLate": null,
    "transactionCount": 3,
    "transactionAmount": 5000
  }
];

// Helper array for converting month number to month name 
var monthNames = ["January", "February", "March", "April", "May", "June",
  "July", "August", "September", "October", "November", "December"
];

input = input
    // Filter out entries where isLate is not 'N':
    .filter( o => o.isLate !== 'N' )
    // Add a new property "mm":
    .map( o => Object.assign(o, { mm: monthNames[+o.month.substr(0,2)-1] }) );

// Display the output
console.log(input);

If you're working on a JavaScript environment without ES6 support, replace the input = statement with:

input = input
    // Filter out entries where isLate is not 'N':
    .filter( function (o) {
        return o.isLate !== 'N'; 
    })
    // Add a new property "mm":
    .map( function (o) {
        o.mm = monthNames[+o.month.substr(0,2)-1];
        return o;
    });

Answer №2

Absolutely, you can achieve this using the filter() method.

const filteredArray = originalArray.filter(item => item.transactionCount !== 1);

In the given example, we are filtering out elements with a transactionCount equal to 1.

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

Unleashing the power of XPath and wildcards in AJAX

Can anyone explain why the variable objProperties, which contains an xpath with a wildcard, is coming up empty in this scenario? function getXMLServerObject (httpType, cmd, isAsync) { var object = new Array(); $.ajax({ type: httpType, ...

Omit child DIV element in JavaScript and the Document Object Model

I have a situation with two div elements. One is <div class="card" id="openWebsite"> and the other is a sub-division <div class="card__btn"> Here's the issue: When someone clicks on the main div, they get red ...

Is it possible to run Next.js 13 with React.js version 17?

Can Next.js 13 be used with React version 17? I upgraded my Next.js to version 13 and encountered a minimum requirement of React version 18, which is not compatible with my codebase. Is it possible to use Next.js 13 with React version 17 instead? ...

Preserving the Selected Date on the Calendar Even After the PHP Variable is Passed

I am currently using the calendar code below with a slight modification that I implemented. However, I have encountered an issue where when I select a date, the calendar successfully highlights the selected date. But once I pass this selected date along ...

Integrating Excel into a webpage - is it possible?

Currently facing an issue on my website. I'm trying to open a 'file://' URL directly with the <a href=""> element in a browser, but it's prohibited. I'm searching for a plugin or similar solution that can enable me to execut ...

What is the best way to split a semicircular border radius in two equal parts?

Is there a way to halve the yellow line or remove it from above the red box, while keeping it below? Can this be achieved using just HTML and CSS, or is JavaScript necessary? * { margin: 0; padding: 0; box-sizing: border-box; } body { height: 1 ...

Updating a JSON file with new object using node.js

Currently, I am attempting to insert a single object into an extensive JSON file. My approach involves parsing the entire file using FS and JSON.Parse, adding the new JSON object in memory, and then rewriting the file. While I am aware of FS's append ...

Ways to remove the uploaded document

I have been tasked with uploading a file. The file comes with a remove button, which can be pressed to delete it. Below is the code I used: The code snippet is as follows: <div id="main"> <p id="addfile1">Add File</p> <div id ...

Understanding the Difference Between WARN and ERR in npm Peer Dependency Resolution

I encountered a puzzling situation where two projects faced the same issue, yet npm resolved them differently: https://github.com/Sairyss/domain-driven-hexagon npm ERR! code ERESOLVE npm ERR! ERESOLVE unable to resolve dependency tree npm ERR! npm ERR! W ...

"The AJAX request triggers an internal 500 error whenever either a post or get request is

Whenever I attempt to submit a post or use the get method from my index.php file which calls Ajax_mysql.php through the Ajax function POST or GET, I encounter a frustrating Internal 500 error. The server doesn't provide any additional information abou ...

Top recommendations for implementing private/authentication routes in NextJS 13

When working with routes affected by a user's authentication status in NextJS 13, what is the most effective approach? I have two specific scenarios that I'm unsure about implementing: What is the best method for redirecting an unauthenticated ...

Referencing an object by using a variable containing its name

I need a way to reference an object using a variable with its name in it. I've figured out how to do this for properties and sub-properties: var req = {body: {jobID: 12}}; console.log(req.body.jobID); //12 var subProperty = "jobID"; cons ...

Issues arise when using Jquery events in conjunction with AngularJS causing them to function

I have encountered an issue with my AngularJS menu code. I am sending an array to prepare the menu when the document loads. In this sequence, I have also added a click event to the generated menu. However, the click event does not fire if it is placed befo ...

Utilizing AJAX to fetch and retrieve a JSON array

Check out the javascript code below: var formSerializedData = $('form#registration-form').serialize(); $.post( '<?php echo $this->url('/register', 'do_register')?>', function(response) { alert(response); } ...

Access the child component within an @ChildComponent directive in Angular

Is it possible to retrieve child components of another component? For instance, consider the following QueryList: @ContentChildren(SysColumn) syscolumns: QueryList<SysColumn>; This QueryList will contain all instances of the SysColumns class, which ...

Tips for refreshing a GET request within a Vue.js application

I am receiving data from my Rails API backend and I would like to automatically refresh that GET request every 15 seconds. This way, if there are any changes on the backend (for example, if a POST request is made to another route), it will reload and retri ...

How to retrieve the width of a document using jQuery?

Having a strange issue with determining the document width using $(document).width() during $(window).load and $(window).resize. The problem arises when the browser is initially full screen and then resized to a narrower width, causing content to require ...

The base64 code generated by the toDataURL method on the canvas appears to be incorrect

I am facing an issue with my code while using canvas to draw a cropped image with base 64. The problem is that it works perfectly on Chrome but gives me a blank image on Firefox. async function base64SquareCrop(imgbase64, size = 224) { const img = docume ...

Can I transfer a variable from JavaScript to Python in a seamless way?

Here's a straightforward query: Is it possible to include a JavaScript variable (varExample) in the data.py line while preserving the functionality of the JSONP Python callback code (?callback=? part)? The objective is to seamlessly integrate varExamp ...

Disable automatic playback of HTML video

There is an HTML video with an image that loads initially and then disappears to play the video. I would like the image to always be visible until I click on it. Once clicked, the video should start playing. You can view the code on JSFiddle: http://jsf ...