如何从数组中选择前两项?

时间:2017-03-29 22:17:24

标签: javascript jquery

我想从数组中选择前2个项目,并从对象中选择每个人的第一个名称,而不是全名。

这些是我的代码:

的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"  
  }
]

这是结果:

  • 他的名字是:Bar​​ot Bellingham,身份:1
  • 他的名字是:alex benjan,id为:2
  • 他的名字是:jony lekson,身份:3

但我想要的是:

  • 他的名字是:Bar​​ot的id为:1
  • 他的名字是:alex的id为:2

你知道怎么做吗?

3 个答案:

答案 0 :(得分:2)

您可以使用slice

for (var key in items.slice(0, 2)) {

但一般建议不要在数组上使用for...in。使用forEach

items.slice(0, 2).forEach(function (item) {
    output += '<li>his name is:' + item.name + ' with the id of:'+ item.id +'</li>';
});

或者,更好的是,将mapjoin结合使用:

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

可以通过使用split的第一个单词来提取名字(这不是100%正确,因为一些名字可能包含两个或更多单词):

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

注意:这与Ajax或JSON几乎没有关系,只需要使用循环和数组方法。

答案 1 :(得分:0)

返回数组的另一种方法:

  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)

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

答案 2 :(得分:0)

通常从数组中获取 2 个第一项:

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

在你的情况下,它会是这样的:

const [first, second] = items.map(({name, id}) => ({firstName: name.split(' ')[0], id}));