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

215
Vistas
How to select first 2 items from an array?

I want to select the first 2 item from an array and also select just first name of each person from an object, not the full name.

These are my codes:

index.html

<body>
<button onclick="loadajax();">laod ajax</button>
<div id = "update"></div>

<script src="jquery.js"></script>
<script src="script.js"></script>
</body>

script.js

function loadajax(){
    var request;
    if (window.XMLHttpRequest) {
        request = new XMLHttpRequest();
    } else {
        request = new ActiveXObject("Microsoft.XMLHTTP");
    }
    request.open('GET', 'data.json');
    request.onreadystatechange = function() {
        if ((request.readyState===4) && (request.status===200)) {
            var items = JSON.parse(request.responseText);
            var output = '<ul>';
            for (var key in items) {
                output += '<li>his name is:' + items[key].name + ' with the id of:'+ items[key].id +'</li>';
            }
            output += '</ul>';
            document.getElementById('update').innerHTML = output;
        }
    }
    request.send();
}

data.json

[
  {
    "name":"Barot Bellingham",
    "id":"1"  
  },
  {
    "name":"alex benjan",
    "id":"2"  
  },
  {
    "name":"jony lekson",
    "id":"3"  
  }
]

this is the results:

  • his name is:Barot Bellingham with the id of:1
  • his name is:alex benjan with the id of:2
  • his name is:jony lekson with the id of:3

but what I want is this:

  • his name is:Barot with the id of:1
  • his name is:alex with the id of:2

do you have an idea how to do this?

over 4 years ago · Santiago Trujillo
3 Respuestas
Responde la pregunta

0

You can use slice:

for (let key in items.slice(0, 2)) { // ...etc

But in general it is advised not to use for...in on arrays. Use for..of (or forEach), in combination with destructuring and a template literal:

for (let {name, id} of items.slice(0, 2)) {
    output += `<li>his name is: ${name} with the id of: ${id}</li>`
}

Or, even better, use map in combination with join:

let output = '<ul>' + items.slice(0, 2).map(({name, id}) =>
    `<li>his name is: ${name} with the id of: ${id}</li>`
).join('') + '</ul>';

The first name can be extracted by taking the first word with split (this is not 100% correct, as some first names can consist of two or more words):

let output = '<ul>' + items.slice(0, 2).map(item =>
    `<li>his name is: ${item.name.split(' ')[0]} with the id of: ${id}</li>`
).join('') + '</ul>';

NB: This has little to do with Ajax or JSON, just with looping and array methods.

over 4 years ago · Santiago Trujillo Denunciar

0

Another approach returning an array:

  var jsonArray = [
  {
    "name":"Barot Bellingham",
    "id":"1"  
  },
  {
    "name":"alex benjan",
    "id":"2"  
  },
  {
    "name":"jony lekson",
    "id":"3"  
  }
];

var user = jsonArray .map((user, index) => { 
        return { 'id': user.id, 'name' : user.name.split(' ')[0] }; 
 }).slice(0, 2)

output: //[{"id":"1","name":"Barot"},{"id":"2","name":"alex"}]

over 4 years ago · Santiago Trujillo Denunciar

0

generally to get 2 first items from array:

 const items = [1, 2, 3]; 
 const [first, second] = items; // 1, 2

In your case it would be like this:

const [first, second] = items.map(({name, id}) => ({firstName: name.split(' ')[0], id}));
over 4 years ago · Santiago Trujillo 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