I'm trying to figure out how to do this in ES6...
I have this array 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"} ];
..and this new array of objects where I want to add each person's total value of 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} ];
I loop through originalData and save each property of the "current object" in a let..
for (let obj of originalData) { let currinvestor = obj.investor; let currinvestment = obj.investment; let currvalue = obj.value; ..but here I want to find the obect in newData that has the property = currinvestor (for the "investor" key) ...then add that investment type's (currinvestment) value (currvalue) }
Answer: Use the find() Method You can simply use the find() method to find an object by a property value in an array of objects in JavaScript. The find() method returns the first element in the given array that satisfies the provided testing function. If no values satisfy the testing function, undefined is returned.
If you need the index of the found element in the array, use findIndex() . If you need to find the index of a value, use Array.prototype.indexOf() . (It's similar to findIndex() , but checks each element for equality with the value instead of using a testing function.)
newData.find(x => x.investor === investor)
And the whole code:
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 }
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With