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:
but what I want is this:
do you have an idea how to do this?
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With