Michael Michael - 2 months ago 10
Javascript Question

Can't get single value after iteration on array of objects

I use this code to iterate on the JavaScript objects array and return value:

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}];


But after iteration is done I expect that
selectedClient
veriable will get single item:

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


But instead
selectedClient
veriable get all items in clients variable.

Any idea why I can't get single value after iteration on
clients
variable?

Answer

You cannot return data from forEach.

Copying from the Lodash Docs for forEach

Iteratee functions may exit iteration early by explicitly returning false.

Use _.find().

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

You can also use shorter syntax with Object as second parameter.

_.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>


For Vanilla Lovers, use 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);

Comments