Good evening guys,
i am trying to merge values in multiple objects in an array and save the result as new key value pairs in the same object. I know how to do it for a single object but not really sure how to archieve it for an array of objects and couldnt find a fitting solution. Do i have to use reduce?
Here is my default array of objects:
let firstObj = [
{
"id": 1,
"firstValue": 45,
"secondValue": 15,
"firstText": "this is ",
"secondText": "a text"
},
{
"id": 2,
"firstValue": 14,
"secondValue": 67,
"firstText": "this is ",
"secondText": "another text"
},
{
"id": 3,
"firstValue": 30,
"secondValue": 71,
"firstText": "this is ",
"secondText": "again a text"
},
{
"id": 4,
"firstValue": 6,
"secondValue": 22,
"firstText": "this is ",
"secondText": "the last text"
}
]
For a single object, i know i could do something like this:
let newObjB = {...firstObj, "total": firstObj.firstValue + firstObj.secondValue, "mergedText": firstObj.firstText + firstObj.secondText}
Like i said, i am not really sure how to archieve it for an array of objects.
It should looks like this:
let firstObj = [
{
"id": 1,
"firstValue": 45,
"secondValue": 15,
"firstText": "this is ",
"secondText": "a text",
"total": 60,
"mergedText": "this is a text"
},
{
"id": 2,
"firstValue": 14,
"secondValue": 67,
"firstText": "this is ",
"secondText": "another text",
"total": 81,
"mergedText": "this is another text"
},
{
"id": 3,
"firstValue": 30,
"secondValue": 71,
"firstText": "this is ",
"secondText": "again a text",
"total": 101,
"mergedText": "this is again a text"
},
{
"id": 4,
"firstValue": 6,
"secondValue": 22,
"firstText": "this is ",
"secondText": "the last text",
"total": 28,
"mergedText": "this is the last text"
}
]
Thanks in advance