Improving the speed of loop in javascript for objects
Continuous repetitive string concatenation is bad for performance because each such operation requires re-hashing of the string due to String interning.
Array enumeration using for-in loop is slower than for-of or a standard for loop.
Things like obj[key][subkey] may be slow in a long loop so cache them in a variable.
Do the proper performance measurements using Devtools Timeline profiler to find bottlenecks.




Here's an arguably more readable and hopefully faster example:

const parts = [];
const group = obj[key];

if (Array.isArray(group)) {
  for (const val of group) {
    if (parts.length) parts.push(', ');
    if (Array.isArray(val)) {
      const tooLong = group.length &gt; 10;
      const len = (tooLong ? group : val).length;
      parts.push(`&lt;font color="green"&gt;Array(${len})&lt;/font&gt;`);
      if (tooLong) break;
    } else {
      parts.push(objectPreview(val));
    }
  }
} else {
  for (const [key, val] of Object.entries(group)) {
    parts.push(`${parts.length ? ', ' : ''}${key}: ${
      Array.isArray(val) ? '[...]' : objectPreview(val)
    }`);
  }
}
const replacements = parts.join('');


function objectPreview(obj) {
  let str = obj;
  switch (typeof obj) {
    case 'object':
      str = '{...}';
      break;
    case 'string':
      if (/&lt;.*?&gt;/.test(obj)) {
        str = type === 'normal' ?
          `&lt;pre&gt;${process(obj).replace(/&lt;/g, '&amp;lt;').replace(/&gt;/g, '&amp;gt;')}&lt;/pre&gt;${obj}` :
          '&lt;font color="red"&gt;"..."&lt;/font&gt;';
      } else {
        str = `&lt;font color="red"&gt;"${obj}"&lt;/font&gt;`;
      }
      break;
    case 'number':
    case 'boolean':
      str = `&lt;font color="#947cf6"&gt;${obj}&lt;/font&gt;`;
      break;
  }
  return str;
}