我想从Javascript中的json文件中获取一些数据

我有这样的json数据:

var bib = {
"AnthesGarcia-HernandezEtAl2016": {
    "author": "C. Anthes and R. J. Garcia-Hernandez and M. Wiedemann and D. Kranzlmuller",
    "booktitle": "2016 IEEE Aerospace Conference",
    "doi": "10.1109/AERO.2016.7500674",
    "file": "AnthesGarcia-HernandezEtAl2016.pdf:AnthesGarcia-HernandezEtAl2016.pdf:PDF",
    "keywords": "virtual reality, survey, aerospace",
},
"Bastos2014": {
    "author": "Bastos, Ricardo S",
    "file": "Bastos2014.pdf:Bastos2014.pdf:PDF",
    "institution": "DTIC Document",
    "keywords": "maritime, military, submarine, training, simulator, virtual reality, web, webgl, navy"

},
"Baum1994": {
    "author": "Baum, David R",
    "keywords": "patent, virtual reality, gestures, aviation, training, head-mounted-display, HMD, gloves",

}


我如何在js中获取数据:

    var keywords = {
    "keywords-name": { // keywords-name as example : virtual reality
        "repeat": "??"

    },
    "keywords-name2": {
       "repeat": "??"
       },
    "keywords-name3": {
       "repeat": "??"
}, ...


我不知道该怎么做。

最佳答案

使用


Object.keys()
Array.prototype.reduce()
Array.prototype.forEach()
String.prototype.split()


您可以这样做:



var bib = {
  "AnthesGarcia-HernandezEtAl2016": {
    "author": "C. Anthes and R. J. Garcia-Hernandez and M. Wiedemann and D. Kranzlmuller",
    "booktitle": "2016 IEEE Aerospace Conference",
    "doi": "10.1109/AERO.2016.7500674",
    "file": "AnthesGarcia-HernandezEtAl2016.pdf:AnthesGarcia-HernandezEtAl2016.pdf:PDF",
    "keywords": "virtual reality, survey, aerospace",
  },
  "Bastos2014": {
    "author": "Bastos, Ricardo S",
    "file": "Bastos2014.pdf:Bastos2014.pdf:PDF",
    "institution": "DTIC Document",
    "keywords": "maritime, military, submarine, training, simulator, virtual reality, web, webgl, navy"
  },
  "Baum1994": {
    "author": "Baum, David R",
    "keywords": "patent, virtual reality, gestures, aviation, training, head-mounted-display, HMD, gloves"
  }
};

var keywords = Object.keys(bib).reduce((a, v) => {
  bib[v].keywords.split(/\s*,\s*/).forEach(kw => {
    a[kw] = a[kw] || {repeat: 0};
    a[kw].repeat++;
  });

  return a;
}, {});

console.log(keywords)

10-06 08:11
查看更多