关于一个js数据结构转换问题

有这么一个评论场景,id是惟一的,answerId和id是对应的,answerId是回复id的人,需要把COMMENT_MOCK_DATA_ORIGIN 数据转化为result数据结构,相当于多了一个字段answerArr为一个回复数组。

var COMMENT_MOCK_DATA_ORIGIN = [
    {
      "id": 52,
      "a_id": 205,
      "user": "用户3",
      "website": "",
      "msg": "王菲菲",
      "createTime": "1533303716",
      answerId:''
    },
    {
      "id": 54,
      "a_id": 205,
      "user": "用户5",
      "website": "",
      "msg": "王菲菲",
      "createTime": "1533303716",
      answerId: 52
    },
    {
      "id": 55,
      "a_id": 205,
      "user": "用户5",
      "website": "",
      "msg": "王菲菲",
      "createTime": "1533303716",
      answerId: 52
    },
    {
      "id": 51,
      "a_id": 205,
      "user": "用户2",
      "website": "",
      "msg": "王菲菲",
      "createTime": "1533303713",
      answerId: 56
    },
    {
      "id": 56,
      "a_id": 205,
      "user": "用户2",
      "website": "",
      "msg": "王菲菲",
      "createTime": "1533303713",
      answerId:''
    },
    {
      "id": 57,
      "a_id": 205,
      "user": "用户2",
      "website": "",
      "msg": "王菲菲",
      "createTime": "1533303713",
      answerId:''
    },
  ]
 var result = [{
    "id": 52,
    "a_id": 205,
    "user": "用户3",
    "website": "",
    "msg": "王菲菲",
    "createTime": "1533303716",
    "answerId": "",
    "answerArr": [{
      "id": 54,
      "a_id": 205,
      "user": "用户5",
      "website": "",
      "msg": "王菲菲",
      "createTime": "1533303716",
      "answerId": 52
    }, 
      {"id": 55, "a_id": 205, "user": "用户5", "website": "", "msg": "王菲菲", "createTime": "1533303716", "answerId": 52}
      ]
  }, {
    "id": 56,
    "a_id": 205,
    "user": "用户2",
    "website": "",
    "msg": "王菲菲",
    "createTime": "1533303713",
    "answerId": "",
    "answerArr": [{
      "id": 51,
      "a_id": 205,
      "user": "用户2",
      "website": "",
      "msg": "王菲菲",
      "createTime": "1533303713",
      "answerId": 56
    }]
  }, {"id": 57, "a_id": 205, "user": "用户2", "website": "", "msg": "王菲菲", "createTime": "1533303713", "answerId": ""}]

问题出现的环境背景及自己尝试过哪些方法

相关代码

// 请把代码文本粘贴到下方(请勿用图片代替代码)

你期待的结果是什么?实际看到的错误信息又是什么?

阅读 1.4k
2 个回答

这是我写的看看有什么缺点可以改进的?

const getMyCommenData=(COMMENT_MOCK_DATA_ORIGIN)=> {
  let mapping = {answerId: []}
  let grande_one = COMMENT_MOCK_DATA_ORIGIN.filter(v => {
    let {answerId = ''} = v;
    if (answerId) {
      mapping[answerId] = []
    }
    return answerId === '' || answerId==null||answerId===0;
  })
  COMMENT_MOCK_DATA_ORIGIN.forEach(v => {
    let {answerId = ''} = v;
    if (answerId in mapping) {
      mapping[answerId].push(v)
    }
  })
  return grande_one.map(v => {
    let {id} = v;
    if (id in mapping) {
      v.answerArr = mapping[id]
    }
    return v;
  });
}

推荐array-to-tree npm 包

var arrayToTree = require('array-to-tree');
arrayToTree(COMMENT_MOCK_DATA_ORIGIN, {
  parentProperty: 'answerId'
})
撰写回答
你尚未登录,登录后可以
  • 和开发者交流问题的细节
  • 关注并接收问题和回答的更新提醒
  • 参与内容的编辑和改进,让解决方法与时俱进
推荐问题