Reputation: 15036
I loop through an array and depending on the conditions I want to add different values to an object.
The first console.log() outputs the value. The second one doesn't output anything. Why? And what can I do about it? The desired outcome is that if any of the keywords is inside nicecontact.fulladress, the string should be splitted and added using that keyword. if none of the values are, I want fulladress=adress
var niceContact= {}
niceContact.fulladress = $.trim(contact[2])
//cut out lgh if it's in there.
var keywords = ["Lgh", "lgh"]
niceContact.adress = keywords.some(function(keyword){
if (niceContact.fulladress.indexOf(keyword) != -1){
adressarray = niceContact.fulladress.split(keyword)
niceContact.adress = adressarray[0]
console.log(niceContact.adress)
return adress;
}else{
console.log('false')
niceContact.adress = niceContact.fulladress
}
})
console.log(niceContact.adress)
Upvotes: 0
Views: 74
Reputation: 10395
Thats not what Array.some
is for. Shouldnt be returning a value from it:
https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/some
some executes the callback function once for each element present in the array until it finds one where callback returns a true value. If such an element is found, some immediately returns true. Otherwise, some returns false. callback is invoked only for indexes of the array which have assigned values; it is not invoked for indexes which have been deleted or which have never been assigned values.
var niceContact= {}
var hadHit = false
niceContact.fulladress = $.trim(contact[2])
//cut out lgh if it's in there.
var keywords = ["Lgh", "lgh"]
niceContact.adress = niceContact.fulladress
keywords.forEach(function(keyword){
if (!hadHit && niceContact.adress.indexOf(keyword) != -1){
// do your checking for the keywords here
// and modify niceContact.adress if needed
// if you're looking to `break` out of the .forEach
// you can `return false;` instead (same as break) see http://stackoverflow.com/questions/6260756/how-to-stop-javascript-foreach
// or if you have a hit, just do `hadHit = true` after mod-ing the address
}
})
console.log(niceContact.adress)
Upvotes: 1