You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何通过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);

步骤说明

  1. 定位目标索引:用findIndex遍历数组,匹配user.username为'motalib'的元素,返回其索引位置。
  2. 调整元素位置:先判断索引有效(避免找不到目标时出错),再通过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

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.29 18:13:21