Empresas
Empleos
  • Sobre nosotros
  • Soluciones
    • Publicación de vacantes
      Publica tu vacante y recibe candidatos calificados en 48h.
    • Evaluación de candidatos
      500+ pruebas técnicas y psicológicas, más anti-fraude.
    • Headhunting
      Búsqueda ejecutiva a la medida de principio a fin.
    • Nómina + EOR
      Dispersión de nómina y EOR en más de 15 países de LATAM.
  • Precios
  • Empleos

0

176
Vistas
How to show the value from an if statement inside a foreach loop in react js?

hello i am using react js, any advice and suggestions are hugely appreciated here. The sharedfields forEach loop does console.log the sharedFieldAlias value, if I console.log it outside of the loop it will not output the value. I need the sharedFieldAlias value to display in the span tag but it gives a reference error that sharedFieldAlias is not defined. How can I display the value in the span tag?

sharedfields.forEach((sharedField) => {
        let sharedFieldAlias = sharedField.alias;
        if(value.shared_field_uuid == sharedField.uuid) {
          console.log(sharedFieldAlias);
        }
      });
      
      const fullLabel = (
        <div style={{ display: 'flex', alignItems: 'center' }}>
          <InputLabel label={display_name} help={parameter.help?.header_id} />
          {!isLinked ? (
            <LinkOutlined onClick={linkField} style={{ color: blue.primary }} />
          ) : (
            <div>
              <CloseSquareOutlined
                onClick={unlinkField}
                style={{ color: yellow[7] }}
              />
              <span className="ant-typography ant-typography-secondary" id="sharedFieldAlias" style={{ marginLeft: '5px', color: '#262626'}}>
                {sharedFieldAlias}
              </span>
            </div>
          )}
        </div>
      );
about 4 years ago · Juan Pablo Isaza
3 Respuestas
Responde la pregunta

0

Declare the variable sharedFieldAlias outside the loop (just above the loop in your case).

let sharedFieldAlias;
<your loop goes here>
about 4 years ago · Juan Pablo Isaza Denunciar

0

You have to declare the variable outside the loop. It might also help to use a for loop instead of forEach so you can break out of the loop once the value is found.

let sharedFieldAlias;
for (const sharedField of sharedfields) {
  if (value.shared_field_uuid == sharedField.uuid) {
    sharedFieldAlias = sharedField.alias;
    console.log(sharedFieldAlias);
    break;
  }
}

about 4 years ago · Juan Pablo Isaza Denunciar

0

There's no need for a global variable. Use find to check the array, find an object where the uuids match, and return the alias, otherwise return 'None'.

const sharedFields = [
  { alias: 'Bob', uuid: '1' },
  { alias: 'Carol', uuid: '2' },
  { alias: 'Sam', uuid: '3' },
  { alias: 'Moses', uuid: '4' }  
];

function getAlias(fields, uuid) {
  const found = fields.find(field => {
    return uuid === field.uuid;
  });
  return found ? found.alias : 'None';
}

console.log(getAlias(sharedFields, '3'));
console.log(getAlias(sharedFields, '31'));
console.log(getAlias(sharedFields, '2'));

Here's a small working example in React.

function getAlias(fields, uuid) {
  const found = fields.find(field => {
    return uuid === field.uuid;
  });
  return found ? found.alias : 'None';
}

function Example({ data }) {

  return (
    <div>
      <div>{getAlias(data, '3')}</div>
      <div>{getAlias(data, '31')}</div>
      <div>{getAlias(data, '2')}</div>
    </div>
  );

}

const data = [
  { alias: 'Bob', uuid: '1' },
  { alias: 'Carol', uuid: '2' },
  { alias: 'Sam', uuid: '3' },
  { alias: 'Moses', uuid: '4' }  
];

ReactDOM.render(
  <Example data={data} />,
  document.getElementById('react')
);
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/17.0.2/umd/react.production.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/react-dom/17.0.2/umd/react-dom.production.min.js"></script>
<div id="react"></div>

about 4 years ago · Juan Pablo Isaza Denunciar
Responde la pregunta
Encuentra empleos remotos

¡Descubre la nueva forma de encontrar empleo!

Top de empleos
Top categorías de empleo
Empresas
Publicar vacante Precios Comercial
Legal
Términos y condiciones Política de privacidad
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomiéndame algunas ofertas
Necesito ayuda