[Solved] Javascript accessing nested properties of an object literal


The line

el.setAttribute(key, [key]);

tries to set the attribute to an array containing the key as its only entry (and thus will set href to "href" since the array will get coerced to string). You probably meant

el.setAttribute(key, obj.att[key]);
// ------------------^^^^^^^

Live Example:

function hoistNav() {
    const nav = [];
    nav[0] = {text: 'HOME', att: {href: "https://stackoverflow.com/questions/48612333/home.html", class: 'nav', id: 'zero'}};
    nav[1] = {text: 'POSTS', att: {href: 'posts.html', class: 'nav', id: 'one'}};
    nav[2] = {text: 'CONTACT', att: {href: 'con.html', class: 'nav', id: 'two'}};
    return nav;
}

function createAnchor(obj) {
    let el = document.createElement('a');
    el.textContent = obj.text;
    for(let key in obj.att){
        el.setAttribute(key, obj.att[key]);
    }
    return el;
}

let nav = hoistNav();

let obj = nav[0];

let anchor = createAnchor(obj);
document.body.appendChild(anchor);
console.log(anchor.outerHTML);

Side note: Not quite sure what hoistNav is for, you could just make nav global to your code (but not actually global):

"use strict"; // Strict mode to ensure correct handling of function decl in block

// Scoping block to avoid creating globals
{

  // Note use of literal notation
  const nav = [
    {text: 'HOME', att: {href: "https://stackoverflow.com/questions/48612333/home.html", class: 'nav', id: 'zero'}},
    {text: 'POSTS', att: {href: 'posts.html', class: 'nav', id: 'one'}},
    {text: 'CONTACT', att: {href: 'con.html', class: 'nav', id: 'two'}}
  ];

  function createAnchor(obj) {
      let el = document.createElement('a');
      el.textContent = obj.text;
      for (let key in obj.att) {
          el.setAttribute(key, obj.att[key]);
      }
      return el;
  }

  // Sample run
  let obj = nav[0];
  let anchor = createAnchor(obj);
  document.body.appendChild(anchor);
  console.log(anchor.outerHTML);
}

3

solved Javascript accessing nested properties of an object literal