【问题标题】:How to get data from json array using names instead of index with jquery如何使用名称而不是使用 jquery 的索引从 json 数组中获取数据
【发布时间】:2016-10-29 16:51:13
【问题描述】:

我一直在尝试使用 jquery 使用名称获取 json 数据,但没有成功,仅适用于对象索引,这是我的代码:

var json = [
   {
      "idiom":[
         {
            "nombre":"español",
            "id":1
         },
         {
            "nombre":"ingles",
            "id":2
         }
      ]
   }
];

console.log(json)
$.each( json[0], function( key, data ) {
$.each(data, function(index, indata) {
console.log(indata.nombre);
});
});

console.log('-------');
$.each( json.idiom, function( key, data ) {
$.each(data, function(index, indata) {
console.log(indata.nombre);
});
});

如果我尝试使用 json.idiom 而不是 json[0] 访问,则代码不起作用

这是一个小提琴:https://jsfiddle.net/wm0de41h/

【问题讨论】:

  • json.idiom 如果你有 json = { "idiom": [ ... ] } 会工作,但你没有...
  • 请正确缩进您的代码。
  • 我这样说是因为我会添加更多数组,而不仅仅是“成语”,这就是为什么 [ ] 开头的原因,例如json = [ {"idiom": [ ... ]}, {"age": [ ... ]}, {"city": [ ... ]} ]
  • 每个对象可以有多个键,你知道吗? { "idiom": [...], "age": [...], "city": [...] } 等不需要数组。

标签: javascript jquery json


【解决方案1】:

您必须访问json[0],因为它是一个包含单个项目的数组。如果您想访问json.idiom,您需要将您的对象重组为:

var json = {
  "idioms":[
    {
       "nombre":"español",
       "id":1
    },
    {
       "nombre":"ingles",
       "id":2
    }
  ]
};

注意您的 json 对象周围现在没有方括号了。 (我还复数了idioms,因为它是一个数组。

最后,您不需要 jquery 来迭代它。您可以使用Array.forEach()

json.idiom.forEach(function(idiom) {
    console.log(idiom.nombre);
});

【讨论】:

  • 谢谢你的回答,我的完整json有三个对象而不是只有一个,是一样的吗?这是我的完整 json:jsfiddle.net/z7ab4t6t
  • 所以你也想要兴趣和estrado,而不仅仅是名词!你在开玩笑吗???
  • 我问是因为我不知道这是否可能,我对此还是很陌生,我认为对于每个具有不同数据的三个对象来说这可能是相同的。
  • @ElrosRomeo 您需要了解更多关于 JSON 对象如何工作以及如何在 Javascript 中遍历它们的信息。我们不会为您编写代码。
  • 我不是要你写代码还是我写了类似的东西?这就是为什么我摆弄我的代码,我只是要求指导以继续尝试修复我的代码。
【解决方案2】:

使用花括号 {} 定义 JSON 对象,而不是使用括号 []。尝试删除括号,这将使您得到以下结果:

var json = {
  "idiom":[
     {
        "nombre":"español",
        "id":1
     },
     {
        "nombre":"ingles",
        "id":2
     }
  ]
};

请参阅MDN 上的 JavaScript 对象文档。

【讨论】:

    猜你喜欢
    • 2018-03-23
    • 2015-07-22
    • 2021-09-16
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2019-05-11
    • 2018-01-16
    • 2013-05-18
    相关资源
    最近更新 更多