How to output an array in Javascript like a social media feed?

I'm using React for my application and I've put my data (objects) into an array. Is there a way to output my data (array of objects) that loads all at once (such as Twitter, Instagram, Facebook)?

Currently I'm using a for loop where it loads one by one from my latest post to the end.

Here's a sample for loop to demonstrate.

var myArray = [
    {name: 'Dwayne', age: 28},
    {name: 'Rob', age: 32},
    {name: 'Marie', age: 22},
    {name: 'Sarah', age: 40},
    {name: 'Emma', age: 29},
    {name: 'James', age: 30}
];

for (var i = myArray.length - 1; i >= 0; i--){
    console.log(myArray[i].name, myArray[i].age);
}

2 answers

  • answered 2018-10-22 15:01 Ted

    Here's an example of using map to generate a <p/> element with name and age inside it.

    render(){
      const myArray = [
        {name: 'Dwayne', age: 28},
        {name: 'Rob', age: 32},
        {name: 'Marie', age: 22},
        {name: 'Sarah', age: 40},
        {name: 'Emma', age: 29},
        {name: 'James', age: 30}
      ];
      return(
        <div>
          {myArray.map((item, index) => (
            <p key={`${item.name}-${index}`}>
              Name:{item.name}, Age:{item.age}
            </p>
          ))}
        </div>
      )
    }
    

    The above code would output

    <div>
      <p>Name:Dwayne, Age:28</p>
      <p>Name:Rob, Age:32</p>
      <p>Name:Marie, Age:22</p>
      <p>Name:Sarah, Age:40</p>
      <p>Name:Emma, Age:29</p>
      <p>Name:James, Age:30</p>
    </div>
    

  • answered 2018-10-22 15:21 Nikolas Freitas Mr Nik

    Create a handler function to help you. Then use that when you receive all you need. the function ComponentDidMount will handle it for you. And with array you use the .map() function, to help you.

    Here is an example:

    import React, { Component } from 'react';
    
    class ShowMyItmes extends Component {
      constructor(props) {
        super(props);
        this.state = {
          peoples: [],
    
        };
      }
    
      componentDidMount() {
        this.setState({
          peoples: renderAllReceived(this.props.peoples),
        })
      }
    
      renderAllReceived(peoples) {
        if (peoples.isArray()) {
          const allImplemented = peoples.map((element, i) => {
            <div key={`${element.name}-${i}`}>
              <p>{`NAME: ${element.name}  AGE:${element.age}`}</p>
            </div>
          });
    
          return allImplemented;
        }
        console.log(("Is not possible get it"));
        return false
      }
    
      render() {
        return (
          <div>
            { this.state.peoples }
          </div>
        );
      }
    }