Which details earlier in "The Gift of the Magi" make the surprise ending logical even though it is startling?
O. Henry takes care to introduce the two possessions owned by the young couple that they took great pride in. With tongue-in-cheek hyperbole, the narrator states that Jim's gold watch that he had received from his father, who had received it from his father, was so impressive that it would have made King Solomon himself envious. Similarly, we learn that Della's hair would be sufficient to make the gifts that the Queen of Sheba bestowed on Solomon pale in comparison. Interestingly, both Jim and Della take great pride in both possessions. Therefore, when Della sells her hair to purchase a chain for Jim's watch, we might surmise (if we had thought of it) that he would be buying something to enhance the great treasure that was Della's that both of them prized, that is, something for her hair.
The other clue we get early in the story that makes the ending logical is the impression that the two young newlyweds are deeply in love with each other. Della wants to buy a gift for Jim that is "something just a little bit near to being worthy of the honor of being owned by Jim." This shows that she idolizes him, and for her to revere him that much, chances are he loves her with a similar devotion. Knowing, then, how much they love each other and how much pride each takes in the other's treasure, it is very logical that each one would sacrifice what was most important to him or her to buy the best present possible for the other.