简体   繁体   English

遍历JSON

[英]Iterating over JSON

I know immediately this is going to be such a simple answer, but my issue here has been when I'm searching for help I can't quite get the search I'm looking for. 我立即知道这将是一个简单的答案,但我的问题一直在寻找帮助时,我无法完全找到想要的搜索。

So I understand basics of how to iterate over a JSON array. 因此,我了解了如何遍历JSON数组的基础知识。 But I want something like the code below to work where what follows 'finaldataset[i]' is a variable rather than a key in the JSON. 但是我希望像下面的代码那样工作,在“ finaldataset [i]”之后是JSON中的变量而不是键。

function iterateOverJSON(s){
for(var i = 0; i<finaldataset.length; i++){
 console.log(finaldataset[i].s)
}
    }

Say finaldataset is an array of movies and attributes about each movie I want to be able to pass the function a value, say "director" or "movieLength", anyway you get the point. 说finaldataset是电影和每个电影的属性的数组,无论如何,无论如何,我都希望能够向函数传递一个值,例如“ director”或“ movieLength”。 Many thanks for any help 非常感谢您的帮助

Use brackets 使用括号

function iterateOverJSON(s){
  for(var i = 0; i<finaldataset.length; i++){
   console.log(finaldataset[i][s])
  }
}

I think you're looking for Array.prototype.map . 我认为您正在寻找Array.prototype.map For example: 例如:

function iterateOverJSON(prop) {
    return finaldataset.map(function(x) { return x[prop]; });
}

// example usage
var directors = iterateOverJSON('director');
var movieLength = iterateOverJSON('movieLength');

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM