ES6: Locate an element within an array based on one of its attributes

Currently experimenting with ES6 and facing a challenge...

I currently have an array consisting of objects:

const originalData=[
{"investor": "Sue", "value": 5, "investment": "stocks"},
{"investor": "Rob", "value": 15, "investment": "options"},
{"investor": "Sue", "value": 25, "investment": "savings"},
{"investor": "Rob", "value": 15, "investment": "savings"},
{"investor": "Sue", "value": 2, "investment": "stocks"},
{"investor": "Liz", "value": 85, "investment": "options"},
{"investor": "Liz", "value": 16, "investment": "options"}
];

My goal is to create a new array of objects where I can calculate the total value for each investor based on their investment types (stocks, options, savings):

const newData = [
{"investor":"Sue", "stocks": 0, "options": 0, "savings": 0},
{"investor":"Rob", "stocks": 0, "options": 0, "savings": 0},
{"investor":"Liz", "stocks": 0, "options": 0, "savings": 0}
];

My approach involves iterating through originalData and storing properties in variables:

for (let obj of originalData) {
   let currinvestor = obj.investor;
   let currinvestment = obj.investment;
   let currvalue = obj.value;

   // Now, I need to locate the object in newData with matching "investor" property...
   // ...and update the corresponding investment type's value accordingly
}

Answer №1

newData.find(x => x.investor === investor)

Here is the complete code snippet:

const originalData = [
  { "investor": "Sue",   "value":  5,   "investment": "stocks"  },
  { "investor": "Rob",   "value": 15,   "investment": "options" },
  { "investor": "Sue",   "value": 25,   "investment": "savings" },
  { "investor": "Rob",   "value": 15,   "investment": "savings" },
  { "investor": "Sue",   "value":  2,   "investment": "stocks"  },
  { "investor": "Liz",   "value": 85,   "investment": "options" },
  { "investor": "Liz",   "value": 16,   "investment": "options" },
];

const newData = [
  { "investor": "Sue",   "stocks": 0,   "options": 0,   "savings": 0 },
  { "investor": "Rob",   "stocks": 0,   "options": 0,   "savings": 0 },
  { "investor": "Liz",   "stocks": 0,   "options": 0,   "savings": 0 },
];

for (let {investor, value, investment} of originalData) {
  newData.find(x => x.investor === investor)[investment] += value;
}

console.log(newData);
.as-console-wrapper.as-console-wrapper { max-height: 100vh }

Answer №2

I think a variation of this code could be helpful:

    const findObjectByProperty = (arr, prop, val) => {
        return arr.find( obj => obj[prop] == val );
    };

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

Finding the offsetWidth (or similar measurement) for a list item (LI) element

Can jQuery be used to determine the width of an element? alert($("#theList li:eq(0)").offsetWidth); <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script> <ol id="theList"> <li>The quick brown ...

Encasing a drop-down menu within a personalized container

I am looking to create a custom HTML element that mimics the behavior of the native <select> element but also triggers a specific update function whenever an attribute or child node is modified. This is essential for incorporating the bootstrap-selec ...

Custom validator failing to trigger ClientValidationFunction

Google may be filled with similar questions, but my issue seems to be a bit unique. What sets it apart is that I am using masked input and have included jquery.maskedinput-1.2.2.js and jquery-1.7.2.min.js in order to utilize masked inputs. The code for mas ...

Ways to verify an array object and an array

Primary list: [VariationSpecificsSet] => SimpleXMLElement Object ( [NameValueList] => Array ( [0] => SimpleXMLElement Object ( ...

I am facing an issue with my $.getJSON() script not functioning as expected

Having trouble getting my JSON / AJAX script to work. I've searched everywhere but can't find a clear explanation of how to use $.getJSON. Can someone please help me out and explain why my code isn't functioning? I suspect the issue lies wit ...

React input field keeps losing focus during re-render operations

My current project involves using React to create an input text that displays a value from an in-memory data store and updates the store when the input value changes, triggering a re-render. However, I am facing an issue where the input text loses focus du ...

Dynamic TextField sizing

I am currently facing an issue while displaying data on a webpage using TextField component from @material-ui. Each record of data has varying lengths, making most values appear unattractive (occupying only 10% of the textfield width). Even though I am ut ...

What is the best way to convert line breaks within a textarea to use <br/> instead?

In my project, I have created a textarea along with a button. This button is designed to replace line breaks within the textarea with <br /> tags. Sample Code: var gtcontbtnafterTA = document.getElementById("contbtnafterTA"); var gtRequesttextare ...

Is picking Slicers in VBA categorized as an Array now that it has evolved into a Data Model?

I need assistance selecting powerpivot slicers with date variables. The slicers represent dates from Monday to Saturday or in the format of 1/19-1/25. I am struggling to figure out how to select the slicers using my date strings for Monday and Saturday, ra ...

An unhandled error occurred when trying to call _this3.setState - it seems like _this3 is not a

I encountered an error when trying to set the data in state in reactjs. Here's the scenario: I am passing data from a child component to a parent component. In the child component, I call the parent function and change the state value using setState. ...

Dynamically apply CSS styles with knockout.js bindings based on conditions

I am looking to apply a conditional css class and a dynamic css class using the css binding feature. For example: data-bind="css: {$data.something() : true, open : showOpen() }" ...

Using Java to reinsert a string into a HashMap

I have this particular String: {Enchantment[minecraft:sharpness, DAMAGE_ALL]=2, Enchantment[minecraft:unbreaking, DURABILITY]=1} and I am trying to convert it back into a Hashmap. Map<Enchantment, Integer> map = new HashMap<>(); Can anyone ...

The efficiency of the react native Animated.spring function leaves much to be desired, as it

I am currently using the React Native animated API to create a seamless transition from left to right positions. This is how I set up my initial state: constructor(props) { super(props); this.state = { isDrawerOpened: false, ...

Displaying dropdown options based on the previous selection made by the user

Can I link the data in my second dropdown to the selection made in the first dropdown? I tried a similar solution from stackoverflow without success. You can find the reference here. The code works when directly copied and pasted but not within my system. ...

Encountered an issue with ReactJS app authentication using Firebase and FirebaseUI. Error message reads: "Uncaught Error: Firebase App named '[DEFAULT]-firebaseui-temp' already exists

I'm currently facing an issue in my code. I am working on a single-page web application in ReactJS with 3 tabs. Whenever the user navigates to one tab, the authentication form from FirebaseUI should appear. However, there seems to be a problem as it ...

Tips on implementing the "remember me" feature using the Amplify Auth Class:

I'm in the process of developing a unique authentication component for an application utilizing Vue and AWS Amplify. One feature I'm looking to implement is a checkbox that allows users to remember their device upon login, eliminating the need fo ...

Waiting for the listener script to finish its task in an Ajax call and then informing the user

I have developed a unique program that allows users to submit test cases from a specific webpage (main.php). The webpage triggers an ajax request to insert user data into MySQL using the file insert.php, with the value done=0. Subsequently, there is a list ...

Upon transitioning to Expo48 Meeting, a new issue has arisen: TypeError - The 'exists' property is unreadable due to being undefined

When I upgraded my project from Expo45 to Expo48, I started encountering an error during testing: TypeError: Cannot read properties of undefined (reading 'exists') at exists (node_modules/expo-asset/src/PlatformUtils.ts:65:17) at asyncGenerator ...

Working with Arrays in jQuery - The $inArray Method

I am encountering an issue where an error message is triggered if there is more than one SKU in the shopping cart. However, I need to make an exception to this rule. Below you can find my code. The scenario I am dealing with is that only the SKU JNL758 ca ...

Unable to activate checkboxes with JavaScript

I have a programming task that involves creating and disabling checkboxes in an ASP.NET website. The checkbox creation code looks something like this: cBox = New CheckBox cBox.ID = "Link" & lngUSN & "|" & objTableMapping.DatasetName & "|" ...