Reputation: 905
I have an array of many json records, which each array contains a subarray. I would like to go thru each array and each of its subarray. there is a field and if the subarray field contains a value like 0, it stops and return a true. basically, stop looping and return a true of the first incident of a 0 value for the code field.
Here is my array/subarray structure
[{id: 0, name: 'test0', mySubArray[{id:0, code: 0},{id:1, code: 1}, {id:2, code: 2} ] }
{id: 1, name: 'test1', mySubArray[{id:1, code: 1},{id:2, code: 2}, {id:3, code: 3} ] }
]
Currenty my code is
getExists() {
exist = this.rows.map(row => (this.doesValueExists(row.mySubArray)))
return exist
}
in my other method
doesValueExists(subArrray) {
let result = _.filter(subArray, 'code', 0)
return result
}
Using lodash, I tried something like this but it did not work
const result = _.map(row, mySubArray => _.filter(mySubArray, 'code', 0))
I am not familiar with lodash, but is there a better way to do this instead of making two calls?
Thanks and appreciated
Upvotes: 0
Views: 542
Reputation: 246
In this case I would use Array.some() method and loop trough each array and it's sub array until "code" is equal to 0. The end code could look like:
const result = values.some(item => item.mySubArray.some(subArray => subArray.code === 0));
"result" value will contain "true" if one of your sub array "code" value is 0.
Upvotes: 1