如何通过username查找数组对象并将其移至数组首位
按指定用户名将数组元素移至首位
完整实现代码
const Post_Comment = [ { "comment": "nice", "user": { "username": "sahed" } }, { "comment": "best", "user": { "username": "motalib" } }, { "comment": "nice.", "user": { "username": "admin" } } ]; // 查找目标用户评论的索引 const targetIndex = Post_Comment.findIndex(item => item.user.username === 'motalib'); // 如果找到目标,移除并移到数组开头 if (targetIndex !== -1) { const [targetComment] = Post_Comment.splice(targetIndex, 1); Post_Comment.unshift(targetComment); } console.log(Post_Comment);
步骤说明
- 定位目标索引:用
findIndex遍历数组,匹配user.username为'motalib'的元素,返回其索引位置。 - 调整元素位置:先判断索引有效(避免找不到目标时出错),再通过
splice移除该元素,最后用unshift将其添加到数组最开头。
最终结果
处理后的Post_Comment数组结构如下:
"Post_Comment": [ { "comment": "best", "user": { "username": "motalib" } }, { "comment": "nice", "user": { "username": "sahed" } }, { "comment": "nice.", "user": { "username": "admin" } } ]
内容的提问来源于stack exchange,提问作者Motalib Hossain
相关产品推荐
相关产品推荐

