微信公众号搜"智元新知"关注
微信扫一扫可直接关注哦!

如何根据对象数组对对象的json数组进行分组

如何解决如何根据对象数组对对象的json数组进行分组

我有一个复杂的对象和数组 json,我想根据标签更改它,我尝试了多种解决方案,但无法修复它。我尝试了 josn 的逻辑组,但这在我的情况下不起作用. 我的 json 对象 =

[{
    "name": "dummy ttile11 house?"
    "tag": ["hospital","car","church"]
},{
    "name": "dummy ttile1 44"
    "tag": ["car","home","office"]
},{
    "name": "dummy ttile11 5546"
    "tag": ["friend","teacher","schools"]
},{
    "name": "dummy ttle"
    "tag": ["father","friend","mother"]
},{
    "name": "dummy ter"
    "tag": ["hospital","mother","home"]
},{
    "name": "dummy tret"
    "tag": ["car",{
    "name": "dummy ttile11"
    "tag": ["hospital","school","library"]
}]

我想把它改成喜欢:

hospital:[title:"ttile",title:"title",title:"title"],car:[title:"ttile",church:[title:"ttile",],home:[title:"ttile",office:[title:"ttile",friend:[title:"ttile",teacher:[title:"ttile",school:[title:"ttile",father:title:"ttile",mother:[title:"ttile",title:"title"]

解决方法

这将为您提供一个带有相关标题的标签对象。

let taglist = data.reduce((b,a) => [...b,...a.tag],[]) // accumulate the tags list
      .filter((v,i,a) => a.indexOf(v) === i),// get only the uniques
      // the first part creates the array of unique tags that we can then iterate through
    tags = taglist.map(t => ({ [t]: data.filter(d => d.tag.includes(t)).map(d => d.name) }))
    // this line maps our list of tags into an object that contains all the associated titles

const data = [{
  "name": "dummy ttile11 house?","tag": ["hospital","car","church"]
},{
  "name": "dummy ttile1 44","tag": ["car","home","office"]
},{
  "name": "dummy ttile11 5546","tag": ["friend","teacher","schools"]
},{
  "name": "dummy ttle","tag": ["father","friend","mother"]
},{
  "name": "dummy ter","mother","home"]
},{
  "name": "dummy tret",{
  "name": "dummy ttile11","school","library"]
}]

const exclude = ['teacher','mother','school','hospital'];
let taglist = data.reduce((b,[]).filter((v,a) => !exclude.includes(v) && a.indexOf(v) === i),tags = taglist.map(t => ({ [t]: data.filter(d => d.tag.includes(t)).map(d => d.name) }))


console.log(tags)

版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。