【问题标题】:fetch json object from json array with a key使用键从 json 数组中获取 json 对象
【发布时间】:2015-03-14 06:58:16
【问题描述】:

我有一个包含一些 json 对象的 json 数组。假设我有一个像这样的course 对象:

{"name": "Math", "unit": "3"}

而我的 json 数组是这样的:

[{"name": "Math", "unit": "3"}, {"name": "Physics", "unit": "3"}, ...]

现在我需要获取一个带有它的名称的对象。例如,我想获得带有“数学”名称的课程。我知道可以循环遍历每个数组项并检查每个项名称并返回一个其名称等于“Math”的对象,但是我的数组可能太长了,循环长数组不好。这可以通过索引访问数组中的对象,例如array[0] 将等于{"name": "Math", "unit": "3"}。但我想用键访问数组,而不是索引。 有没有更好的解决方案来做到这一点?任何帮助将不胜感激。

【问题讨论】:

标签: javascript jquery arrays json


【解决方案1】:

你可以使用 jQuery 的.grep()

var newArray = $.grep(obj, function(item){ return item.name == "Math"; });

【讨论】:

  • 如果你不介意,你能提供一个 jsfiddle 演示吗?@Dhiraj Bodicherla
【解决方案2】:

如果您需要对该数组进行乘法查询,建议您使用以下代码将数组转换为 json 对象:

var newObj = yourArray.reduce(function(previousValue, currentValue, index, array) {
  return previousValue[currentValue.name] = currentValue;
}, {});

你会得到:

{"Math":{"name": "Math", unit: "3"}, "Physics":{"name": "Physics", unit: "3"}, ...}

您只能循环一次,但以后可以重复使用。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2023-01-17
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-03-04
    • 1970-01-01
    • 2021-03-10
    • 1970-01-01
    相关资源
    最近更新 更多