Ad

How To Deal With Array Of Objects? I Have An Array With 3 Objects Containing JSON Data From My Db

- 1 answer

Basically, I have an array of posts that contains 3 objects: posts[{},{},{}]

Each object looks something like this:

1: Object
__v: 0
_id: "5686e17fc64feafd4486f22c"
created_at: "2016-01-01T20:28:47.889Z"
image: "Test"
message: "Test"
title: "Test Post 1"
updated_at: "2016-01-01T20:28:47.889Z"

I'm wondering how I can get an index or something of each object, but also use that for the object's properties.

I was testing earlier with an object of objects, and all I had to do there was: Object.keys(this.props.data).map(this.renderPostTile). Then I could just use a parameter for renderPostTile(key).

How can I do something similar when I have an array of objects?

enter image description here

Ad

Answer

Like this:

var posts = [
  { title: "Test Post 1" },
  { title: "Test Post 2" },
  { title: "Test Post 3" }
];

posts.map(function(post){
  var p = document.createElement("p"),
      t = document.createTextNode(post.title);
  p.appendChild(t);
  document.body.appendChild(p);
});

Obviously your objects are more complicated, but you get the idea.

Edit:

React-wise, you could do something like this:

var PostListRender = React.createClass({
  render: function() {
    return (
      <ul>
        {this.props.posts.map(function(post){
          return <li>{post.title}</li>;
        })}
      </ul>
    )
  }
});

var posts = [
  {title: "Test Post 1"}, 
  {title: "Test Post 2"}, 
  {title: "Test Post 3"}
];

var el = document.getElementById('post-container');
React.render( < PostListRender posts = {posts} />, el);

Demo

Ad
source: stackoverflow.com
Ad