At first glance it does seem odd that John would leave this command dangling on the end of his letter. Why would he suddenly mention idols and not say anything more on the subject when he hasn't spoken about idols at all his letter. One explanation is that John had more to say about idol worship but his letter as it now stands is unfinished.
But this reference to idols is not at all out of step with the rest of John's letters. In fact idolatry could have been misconstrued as his point by some in his original audience if he had not added this command at the very end of his gospel.
John is combating a heretical teaching which claimed that Jesus did not come in the flesh. 1 John states
4:4 Dear friends, do not believe every spirit, but test the spirits to
see whether they are from God, because many false prophets have gone
out into the world. 2 This is how you can recognize the Spirit of God:
Every spirit that acknowledges that Jesus Christ has come in the flesh
is from God, 3 but every spirit that does not acknowledge Jesus is not
from God. This is the spirit of the antichrist, which you have heard
is coming and even now is already in the world.
And 2 John 7 we read
7 I say this because many deceivers, who do not acknowledge Jesus
Christ as coming in the flesh, have gone out into the world. Any such
person is the deceiver and the antichrist.
This explains in part John's reference to blood and water in 1 John 5:6
5:6 This is the one who came by water and blood—Jesus Christ. He did
not come by water only, but by water and blood.
John pushes back against this teaching, emphasizing the tangibility of the Word in 1 John
1:1 That which was from the beginning, which we have heard, which we
have seen with our eyes, which we have looked at and our hands have
touched—this we proclaim concerning the Word of life. 2 The life
appeared; we have seen it and testify to it, and we proclaim to you
the eternal life, which was with the Father and has appeared to us. 3
We proclaim to you what we have seen and heard, so that you also may
have fellowship with us.
With all this emphasis on the tangibility of God in Jesus it probably would have been tempting for John's gentile audience to think in terms of idol worship. If God was manifested physically in Jesus why wouldn't they think that John was giving them permission to worship a tangible image of God like their former way of life and like surrounding culture.
But John adds this final command, almost as an afterthought, a post script, to prohibit this line of thinking. The tangibility of God in Jesus does not give us permission to worship idols.