2

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);
});

9 Answers 9

4

You can use the .reduce function:

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

=> 121212

Sign up to request clarification or add additional context in comments.

2 Comments

what about the case when data[i].details.Closed is undefined
In the case that a field is undefined, you can write item.details?.Closed ?? '' instead of item.details.Closed. If item.details.Closed is null-ish, it would return an empty string: data.reduce((accumulator, item) => accumulator += item.details?.Closed ?? '', '')
2

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 })

2 Comments

@Naren- If i have another property "Analyze" along with "Closed", how can i concatenate values of both these in single reduce ?
You can use object to saved all strings as a result. let me do that
2

Try the following:

const data = [
    {
      "personId": "1208007855",
      "details": {
        "Closed": "12"
      }
    },
    {
      "personId": "1559363884",
      "details": {
        "Closed": "12"
      }
    },
    {
      "personId": "973567318",
      "details": {
        "Closed": "12"
      }
    }
  ];
  result = '';
  for (let i in data) {
      result += data[i].details.Closed
  }

2 Comments

What about the case when data[i].details.Closed is undefined
In that case use result = ''; for (let i in data2) { if (typeof data2[i]?.details?.Closed != 'undefined') result += data2[i]?.details?.Closed }
2

If you want a string and have an array, the best method is reduce:

const totalClosed = data.reduce(function (accumulator, currentVal) {
    const closed = currentVal.details.Closed || '';
    return accumulator + closed;
}, '');

Comments

2

Using foreach exactly the same way you were trying:

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

let totalClosed = '';

data.forEach(function (arrayItem) {
  totalClosed = totalClosed + arrayItem.details.Closed;
});

console.log(totalClosed);

Comments

1
let str = "";
for(let i=0; i<data.length;i++){
str+= data[i].details.Closed;
}

console.log(str);

Also, with forEach, the elements might not be processed in the same order (0 to n) and you may find different results than you expect.

Comments

1
let str = ''
const totalClosed = data.forEach(function (arrayItem) {
  if(arrayItem.details.Closed){
        str += arrayItem.details.Closed;
  }
});

console.log(str)

You can create an empty string and add to it if the closed field exists, if there is another condition in 'Closed' you can check there in the if statement.

Comments

1

You can reduce the data entries by destructuring the entry in the reducer and concatenating the Closed value to the running res (result). You can use the nullish-coalescing operator (??) to use an empty string instead of undefined when concatenating.

const data = [
  { "personId": "1208007855" , "details": { "Closed": "12" } },
  { "personId": "1559363884" , "details": { "Closed": "12" } },
  { "personId": "0000000000" , "details": { "Open"  : "8"  } }, // New!
  { "personId": "973567318"  , "details": { "Closed": "12" } }
];

const value = data.reduce((res, { details: { Closed } }) => res + (Closed ?? ''), '');

console.log(value);

Comments

1

If you want to implement using loops Try Using:

const data = [
    {
      "personId": "1208007855",
      "details": {
        "Closed": "12"
      }
    },
    {
      "personId": "1559363884",
      "details": {
        "Closed": "12"
      }
    },
    {
      "personId": "973567318",
      "details": {
        "Closed": "12"
      }
    }
  ];
var res= ''
data.forEach((item)=>{if(item.details.Closed){ res += item.details.Closed;}})
console.log(res)

And this can also be done by using higher order functions: Try using :

data.reduce((res, item) =>{if(item.details.Closed)
 res += item.details.Closed;
return res}, '')

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.