[英]How to deal with array of objects? I have an array with 3 objects containing JSON data from my db
Basically, I have an array of posts
that contains 3 objects: posts[{},{},{}] 基本上,我有一个包含3个对象的posts
数组: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)
. 我之前在测试对象的对象,而我要做的就是: Object.keys(this.props.data).map(this.renderPostTile)
。 Then I could just use a parameter for renderPostTile(key)
. 然后,我可以只为renderPostTile(key)
使用一个参数。
How can I do something similar when I have an array of objects? 当我有一个对象数组时,如何做类似的事情?
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);
Object.keys
returns an Array, that's why you can do .map()
on it, which is an Array method. Object.keys
返回一个Array,这就是为什么您可以在其上执行.map()
的原因,这是一个Array方法。 So yeah, you can utilize map on the Array. 是的,您可以在Array上利用map。 Literally just call posts.map(myCallback);
从字面上看只是调用posts.map(myCallback);
You're literally taking something where you converted an Object's keys INTO an Array for the purposes of using an Array method on it and asking "Can I do this to an Array too?" 您实际上是在将对象的键转换为Array的目的,目的是在其上使用Array方法并询问“我也可以对Array这样做吗?” The answer is "well...of course, you just don't have to convert it to anything first...just call the Array's .map method" . 答案是“好吧……当然,您不必先将其转换为任何东西……只需调用Array的.map方法即可” 。
You keep saying it says that postData.map
isn't a function...but you say your Array is named posts
...so it would be posts.map
. 您一直说它说postData.map
不是一个函数...但是您说您的Array被命名为posts
...所以它将是posts.map
。 If whatever you're working with doesn't have a map method, then it's not an Array (at least in modern browsers). 如果您使用的任何方法都没有map方法,则它不是数组(至少在现代浏览器中)。 Make sure you're calling it on the Array. 确保在阵列上调用它。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.