Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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?

like image 429
Alex Avatar asked Sep 05 '25 03:09

Alex


1 Answers

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.

like image 196
trincot Avatar answered Sep 07 '25 21:09

trincot