They didn’t evolve in the sense that they were naturally selected to be loyal and affectionate. They were unnaturally (artificially) selected by humans for generations for those qualities, and for other qualities. For example, the American Kennel Club has specific definitions of what a dog’s appearance and temperament are for them to be a member of a breed, like Golden Retriever, and if the dog doesn’t conform, it isn’t bred with other dogs of that breed.
In other words, dogs are loyal and affectionate because people made them that way over time, and humans have associated with dogs for about 30,000 years. What we have now is what 30,000 years of selective breeding can do to wolves.
Latest Answers