【发布时间】:2018-12-05 11:39:07
【问题描述】:
This answer is already close,并且有一些答案如何在数组中获取唯一值(删除重复项),尽管我无法使其适用于关于对象数组的情况,以及应该的属性被过滤的是一个数组。对不起,我是一个JS新手。感谢您的帮助。
我有一个这样的对象数组
const posts = [
post1: {
id: 1,
title: 'One',
tags: ['tagA', 'tagB']
},
post2: {
id: 2,
title: 'Two',
tags: ['tagB', 'tagC']
},
post3: {
id: 3,
title: 'Three',
tags: ['tagB', tagC, tagD]
]
我需要的是一个包含所有唯一标签的数组......在上面的例子中,预期的输出是这样的:
// [tagA, tagB, tagC, tagD]
编辑/更新
对象数组中的键用于管理反应组件的状态...例如
constructor(props) {
super(props);
this.state = {
posts: []
};
}
...
updatePost = (key, updatedPost) => {
//1. Take copy of the current this.state.
const posts = {...this.state.texts};
//2. Update that state
posts[key] = updatedPost;
//3. Set that to state
const options = { encrypt: false }
putFile(postsFileName, JSON.stringify(posts), options)
.then(() => {
this.setState({
posts: posts
})
})
};
【问题讨论】:
-
您的帖子不是有效的 JS,它应该是您的数组中的直接对象吗?
-
这不是一个有效的数组。
-
如果您不明白他们在说什么,
posts是一个数组,post1、post2、post3将是对象中的键,而不是数组。您是否错误地复制了某些内容? -
对不起,伙计们,如果我在这里使用了错误的术语,我们深表歉意。这就是我所说的“对象数组”,是我在添加帖子后在我的反应组件中获得的状态。添加密钥以管理/更新帖子...参见上面的“编辑/更新”。
标签: javascript arrays filter unique