Home > Net >  How do I Output a value of a nested object in Javascript after looping through?
How do I Output a value of a nested object in Javascript after looping through?

Time:07-10

I'm having some trouble printing out some of my data of a forEach loop. I'm working on a Twitter clone and I'm trying to loop through an object and print out the tweets for a user. I'm getting the divs to print out in the console but I can't seem to figure out to get the tweets to print inside the div.

Any help would be appreciated.

var user1 = {
  userName: '@elonmusk',
  displayName: 'Elon Musk',
  joinedDate: 'June 2009',
  followingCount: 103,
  tweetAmount: 18600,
  followerCount: 47900000,
  avatarURL: 'assets/elonmusk.jpg',
  coverPhotoURL: 'assets/elonmusk-cover.jpeg',
  tweets: [{
      text: 'I admit to judging books by their cover',
      timestamp: '2/10/2021 00:01:20'
    },
    {
      text: 'Starship to the moon',
      timestamp: '2/09/2021 18:37:12'
    },
    {
      text: 'Out on launch pad, engine swap underway',
      timestamp: '2/09/2021 12:11:51'
    }
  ]
};

var container = document.getElementById('container');
var midSection = document.getElementById('mid-section')
var sections = document.createElement('div');
sections.classList.add('container');

sections.innerHTML = `
    <div ></div>
    <div >
        <div id="header">
            <img  src="./assets/arrow-left.svg" />
          <div >
            <h2>${user1.displayName}</h2>
        <div >${user1.tweetAmount}K Tweets</div>
        </div>
        </div>
        <div ><img src="${user1.coverPhotoURL}"/></div>
        <div id="avatar">
        <div ><img src="${user1.avatarURL}"/></div>
        <div >
            <button ><img src="./assets/three-dots.svg"/></button>
            <button >Follow</button>
        </div>
        </div>
        <h2 >${user1.displayName}</h2>
        <div >${user1.userName}</div>
        <div >Joined ${user1.joinedDate}</div>
        <div >
        <p><span >${user1.followingCount}</span> Following</p>
        <p ><span >${user1.followerCount}</span> Followers</p>
        </div>

        <div >
           <div >Tweets</div>
           <div >Tweets & replies</div>
           <div >Media</div>
           <div >Likes</div>
        </div>
        <div >
      
        </div>
    </div>

    <div ></div>
`;

var user1Tweets = user1.tweets;

var tweetDivs = user1Tweets.map((tweetDiv) => {
  if (!tweetDiv.tweets) {
    return { ...tweetDiv,
      tweets: []
    };
  } else if (!Array.isArray(tweetDiv.tweets)) {
    return { ...tweetDiv,
      tweets: Object.values(tweetDiv.tweets)
    };
  }
  return tweetDiv;
});

tweetDivs.forEach(function(tweetDiv, i) {
  var tDiv = document.createElement('div');
  tDiv.classList.add('tweetDiv');
  tDiv.innerHTML = `

    ${tweetDiv.tweets.map(function(tweet) {
        return `<div>${tweet}</div>`
    })}
  
    `;
  //console.log(tDiv)
  midSection.appendChild(tDiv);
})

container.appendChild(sections);
<script src="https://cdn.jsdelivr.net/npm/[email protected]/dist/js/bootstrap.bundle.min.js" integrity="sha384-pprn3073KE6tl6bjs2QrFaJGz5/SUsLqktiwsUTF55Jfv3qYSDhgCecCxMW52nD2" crossorigin="anonymous"></script>

<div id="container">
  <div id="mid-section"></div>
</div>

CodePudding user response:

user1.tweets is an array. So you can iterate over the array, get the text from each object, and do something with it.

var user1 = {
  tweets: [{
      text: 'I admit to judging books by their cover',
      timestamp: '2/10/2021 00:01:20'
    },
    {
      text: 'Starship to the moon',
      timestamp: '2/09/2021 18:37:12'
    },
    {
      text: 'Out on launch pad, engine swap underway',
      timestamp: '2/09/2021 12:11:51'
    }
  ]
};


var midSection = document.getElementById('mid-section')

user1.tweets.forEach(function(tweetDiv, i) {
  var tDiv = document.createElement('div');
  tDiv.classList.add('tweetDiv');
  tDiv.innerHTML = tweetDiv.text;
  midSection.appendChild(tDiv);
})
<div id="mid-section"></div>

CodePudding user response:

Because you already have access to the array, so you can destruct it

tweetDivs.forEach(({text, timestamp}) 

and then do this:

`<span>${text}, ${timestamp}</span>`

Also improve your code a bit for es6 (arrow functions, variables to const)

Snippet below

const container = document.getElementById('container');
const midSection = document.getElementById('mid-section')
const user1 = {
  userName: '@elonmusk',
  displayName: 'Elon Musk',
  joinedDate: 'June 2009',
  followingCount: 103,
  tweetAmount: 18600,
  followerCount: 47900000,
  avatarURL: 'assets/elonmusk.jpg',
  coverPhotoURL: 'assets/elonmusk-cover.jpeg',
  tweets: [{
      text: 'I admit to judging books by their cover',
      timestamp: '2/10/2021 00:01:20'
    },
    {
      text: 'Starship to the moon',
      timestamp: '2/09/2021 18:37:12'
    },
    {
      text: 'Out on launch pad, engine swap underway',
      timestamp: '2/09/2021 12:11:51'
    }
  ]
};


const sections = document.createElement('div');
sections.classList.add('container');

sections.innerHTML = `
    <div ></div>
    <div >
        <div id="header">
            <img  src="./assets/arrow-left.svg" />
          <div >
            <h2>${user1.displayName}</h2>
        <div >${user1.tweetAmount}K Tweets</div>
        </div>
        </div>
        <div ><img src="${user1.coverPhotoURL}"/></div>
        <div id="avatar">
        <div ><img src="${user1.avatarURL}"/></div>
        <div >
            <button ><img src="./assets/three-dots.svg"/></button>
            <button >Follow</button>
        </div>
        </div>
        <h2 >${user1.displayName}</h2>
        <div >${user1.userName}</div>
        <div >Joined ${user1.joinedDate}</div>
        <div >
        <p><span >${user1.followingCount}</span> Following</p>
        <p ><span >${user1.followerCount}</span> Followers</p>
        </div>

        <div >
           <div >Tweets</div>
           <div >Tweets & replies</div>
           <div >Media</div>
           <div >Likes</div>
        </div>
        <div >
      
        </div>
    </div>

    <div ></div>
`;

const user1Tweets = user1.tweets;

const tweetDivs = user1Tweets.map((tweetDiv) => {
  if (!tweetDiv.tweets) {
    return { ...tweetDiv,
      tweets: []
    };
  } else if (!Array.isArray(tweetDiv.tweets)) {
    return { ...tweetDiv,
      tweets: Object.values(tweetDiv.tweets)
    };
  }
  return tweetDiv;
});

tweetDivs.forEach(({text, timestamp}) => {
  const tDiv = document.createElement('div');
  tDiv.classList.add('tweetDiv');
  tDiv.innerHTML = `<span>${text}, ${timestamp}</span>`
  
  midSection.appendChild(tDiv);
})

container.appendChild(sections);
<script src="https://cdn.jsdelivr.net/npm/[email protected]/dist/js/bootstrap.bundle.min.js" integrity="sha384-pprn3073KE6tl6bjs2QrFaJGz5/SUsLqktiwsUTF55Jfv3qYSDhgCecCxMW52nD2" crossorigin="anonymous"></script>

<div id="container">
  <div id="mid-section"></div>
</div>

  • Related