迭代对象数组后无法获得单个值

时间:2016-06-09 12:50:54

标签: javascript lodash

我使用此代码迭代JavaScript对象数组并返回值:

this.selectedClient = _.forEach(self.clients, function (client) {
    if (client.IdentityNumber == -1) {
        return client;
    }
}) 

this.clients=[{firstName:"Tywin", lastName:"Lannister", age:46, IdentityNumber:2},
              {firstName:"Arya", lastName:"Starck", age:46, IdentityNumber:-1},
              {firstName:"John", lastName:"Snow", age:46, IdentityNumber:12},
              {firstName:"Robb", lastName:"Starck", age:46, IdentityNumber:24}];

但是迭代完成后,我希望selectedClient veriable将获得单项:

{firstName:"Arya", lastName:"Starck", age:46, IdentityNumber:-1}

但是selectedClient可以获得客户变量中的所有项目。

知道为什么我在clients变量上迭代后无法获得单值?

1 个答案:

答案 0 :(得分:4)

您不能return来自forEach的数据。

从Lodash文档中复制forEach

  

Iteratee函数可以通过显式返回false来提前退出迭代。

使用_.find()

var selectedClient = _.find(clients, function (client) {
    if (client.IdentityNumber == -1) {
        return client;
    }
});

您还可以使用较短的语法和Object作为第二个参数。

_.find(clients, {IdentityNumber: -1});

var clients = [{
    firstName: "Tywin",
    lastName: "Lannister",
    age: 46,
    IdentityNumber: 2
}, {
    firstName: "Arya",
    lastName: "Starck",
    age: 46,
    IdentityNumber: -1
}, {
    firstName: "John",
    lastName: "Snow",
    age: 46,
    IdentityNumber: 12
}, {
    firstName: "Robb",
    lastName: "Starck",
    age: 46,
    IdentityNumber: 24
}];


var selectedClient = _.find(clients, {IdentityNumber: -1});

console.log(selectedClient);
<script src="https://cdn.jsdelivr.net/lodash/4.13.1/lodash.min.js"></script>

对于Vanilla Lovers,请使用Array#find

clients.find(c => c.IdentityNumber === -1)

var clients = [{
    firstName: "Tywin",
    lastName: "Lannister",
    age: 46,
    IdentityNumber: 2
}, {
    firstName: "Arya",
    lastName: "Starck",
    age: 46,
    IdentityNumber: -1
}, {
    firstName: "Robb",
    lastName: "Starck",
    age: 46,
    IdentityNumber: 24
}];

var selectedClient = clients.find(c => c.IdentityNumber === -1);
console.log(selectedClient);