Search code examples
javascriptobjecttype-conversionmeta

How do I convert the "name" and "content" attributes of specific meta tags into a JavaScript object literal?


I have several meta tags that look like this:

<meta name="Addan:id" content="2098949824982" />
<meta name="Addan:name" content="Addan Salahehin" />

How do I convert these meta tags (there is more than 1) into a JavaScript object that looks this:

{ "id" : "2098949824982" , "name" : "Addan Salahehin" }

I've tried to use the forEach method but Addan isn't getting removed.

I'd like to use Vanilla JS and not jQuery.


Solution

  • You might be getting this error because you are not removing or checking for the "Addan:" part of your meta's name, try using this instead:

    let metas = {};
    [...document.querySelectorAll("meta")].forEach(meta => {
      const split = meta.name.split(":");
      if (split[0].trim().toLowerCase() == "addan") {
        metas[split[1]] = meta.content;
      }
    });
    console.log(metas);
    <meta name="Addan:id" content="2098949824982" />
    <meta name="Addan:name" content="Addan Salahehin" />

    When you run the snippet, you should get this output:

    Object { id: "2098949824982", name: "Addan Salahehin" }
    

    NOTE: Here is a working code pen.