如何基于密钥中的字符串获取密钥和json字符串的值

时间:2020-11-02 13:45:39

标签: json ecmascript-6 ecmascript-5 javassist

我有一个如下所示的JSON文件:

{
"rooms":{
  "operatorLimbo":[
     
  ],
  "pager":[
     "w0vu9ourxkdpkf0vwosrim",
     "mekkgn9e9kdpwf2rzpkf41",
     "upkicevngkd5s2h8o01wyz",
     "x29ywtag4kfs0mylq2rd4v"
  ],
  "ru_pagers":[
     "mekkgn9e9kdpwf2rzpkf41"
  ],
  "ch_pagers":[
     "upkicevngkd5s2h8o01wyz"
  ],
  "operators":[
     "r9agylhvekcoibhrk8db8c",
     "p94jb2ocyk5hv0ch8tivk5",
     "v7cxhqxa3kdgik1h4t1sx0",
     "spuvkm9nnketwnqeelqzbf"
  ],
  "pl_operators":[
     "spuvkm9nnketwnqeelqzbf"
  ],
  "clients":[
     "g99g943hlkh0kp1864rwpz",
     "prky4witjkh0naaswiewzs"
  ],
  "pl_users":[
     
  ],
  "ru_operators":[
     "r9agylhvekcoibhrk8db8c"
  ],
  "ch_operators":[
     "v7cxhqxa3kdgik1h4t1sx0"
  ],
  "nl_operators":[
     "p94jb2ocyk5hv0ch8tivk5"
  ],
  "nl_pagers":[
     "w0vu9ourxkdpkf0vwosrim"
  ],
  "ch_users":[
     "prky4witjkh0naaswiewzs"
  ],
  "nl_users":[
     "g99g943hlkh0kp1864rwpz"
  ],
  "pl_pagers":[
     "x29ywtag4kfs0mylq2rd4v"
  ],
  "ru_users":[
     
  ],
  "us_operators":[
     
  ],
  "au_operators":[
     
  ],
  "au_users":[
     
  ],
  "au_pagers":[
     
  ],
  "za_operators":[
     
  ],
  "yoiqfvvvokh0kp2v53sic9":{
     "roomid":"yoiqfvvvokh0kp2v53sic9",
     "type":"1to1",
     "ujid":"g99g943hlkh0kp1864rwpz",
     "aid":"3173aaacd43941c7bef1a99e0057ba2b",
     "operator":{
        "fullname":"Operator",
        "name":"Operator",
        "lastname":"Jura"
     },
     "members":[
        "Ss0G3RCClvOO8I03AAIp",
        "jZGZ_yAb-SC3bEpmAAJz"
     ],
     "chatRecord":11151,
     "ojid":"p94jb2ocyk5hv0ch8tivk5",
     "usid":"jZGZ_yAb-SC3bEpmAAJz"
  },
  "deomjtr27kh0l52ogg9zxh":{
     "roomid":"deomjtr27kh0l52ogg9zxh",
     "type":"1to1",
     "ujid":"prky4witjkh0naaswiewzs",
     "aid":"3173aaacd43941c7bef1a99e0057ba2b",
     "operator":{
        "fullname":"Operator",
        "name":"Operator",
        "lastname":"Jura"
     },
     "members":[
        "DPeOVb1P6qCVXO6GAAJi",
        "AAkb84mpMxLzFHklAAJ7"
     ],
     "chatRecord":11153,
     "ojid":"v7cxhqxa3kdgik1h4t1sx0",
     "usid":"AAkb84mpMxLzFHklAAJ7"
  }
  }
}

我感兴趣的是获取ch_operators和pl_operators等值,基本上所有包含_operators的条目以及它的值,

使用以下代码,我只能得到键,也要如何获得值,

Object.keys(this.rooms).filter((key) => key.includes("_operators"))

任何帮助将不胜感激。

1 个答案:

答案 0 :(得分:0)

您可以结合使用Object.entries.filterObject.fromEntries来创建具有选定属性的新对象:

Object.fromEntries(
  Object.entries(this.rooms).filter(([key]) => key.includes("_operators"))
)

Object.entries返回一个包含键和值的数组(作为“元组”),而Object.fromEntries从该数组中构建一个新对象。