Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Concatenate strings within array of objects

I have the array of objects as below. I want to loop through it and get Closed property values. It should be a concatenation of all the values found in each object.

For e.g. in below case, i want final result as 121212 since it has 12 in all the 3 objects.

const data = [
    {
      "personId": "1208007855",
      "details": {
        "Closed": "12"
      }
    },
    {
      "personId": "1559363884",
      "details": {
        "Closed": "12"
      }
    },
    {
      "personId": "973567318",
      "details": {
        "Closed": "12"
      }
    }
  ]

can someone let me know how to achieve this. I tried this way but couldnt succeed in achieving the result. I could only get the value of first object. Not sure how i can concatenate and store next values in this loop

There might be a situation where some objects might not have Closed property.

const totalClosed = data.forEach(function (arrayItem) {
    const x = arrayItem.details.Closed;
    console.log(x);
});
like image 846
Aren Trot Avatar asked Jun 13 '26 23:06

Aren Trot


2 Answers

You can use the .reduce function:

data.reduce((accumulator, item) => accumulator += item.details.Closed, '')

=> 121212

like image 96
djaax Avatar answered Jun 16 '26 17:06

djaax


In functional way, using reduce

const data = [
    {
        "personId": "1208007855",
        "details": {
            "Closed": "12",
            "Analyze": "10"
        }
    },
    {
        "personId": "1559363884",
        "details": {
            "Closed": "12",
            "Analyze": "10"
        }
    },
    {
        "personId": "973567318",
        "details": {
            "Closed": "12",
            "Analyze": "10"
        }
    }
]

const { Closed, Analyze } = data.reduce((acc, cur) => {
    acc.Closed += cur?.details?.Closed ?? ''
    acc.Analyze += cur?.details?.Analyze ?? ''
   return acc
}, { Closed: "", Analyze: "" })
console.log({ Closed, Analyze })
like image 44
Naren Avatar answered Jun 16 '26 17:06

Naren



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!