Business
Jobs
  • About Us
  • Solutions
    • Job Postings
      Post your job and receive qualified candidates in 48h.
    • Candidate Assessments
      500+ technical and psychological tests, plus anti-fraud.
    • Headhunting
      Tailor-made executive search from start to finish.
    • Payroll + EOR
      Payroll dispersal and EOR across 15+ LATAM countries.
  • Pricing
  • Jobs

0

212
Views
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 answers
Answer question

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 Report

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 Report

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 Report
Answer question
Find remote jobs

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post vacancy Pricing Sales
Legal
Terms and conditions Privacy policy
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Show me some job opportunities
There's an error!