The reason for the child's death is clearly given in II Samuel 12:14 :
... because by this deed thou hast given great occasion to the enemies of the Lord to blaspheme, the child also that is born unto thee shall die. [KJV]
The Lord had promised to David, by the mouth of Nathan the prophet :
... I will set up thy seed after thee, which shall proceed out of the bowels, and I will establish his kingdom. [II Samuel 7:12. KJV.]
This, of course, is prophetic not only of David's immediate seed (later to be seen in Solomon) but also prophetic of the everlasting kingdom to be set up through the reign of the son of David, Jesus Christ.
But neither the figure of the everlasting kingdom (Solomon) nor the fulfillment of that figure (the one born of the virgin Mary) would be permitted to come from the child born out of David's transgression.
The fruit of that transgression was not to be the one to fulfill either the figure or the reality of the everlasting kingdom.
The Lord gave and the Lord hath taken away; blessed be the name of the Lord, Job 1:21.