jquery:如何通过另一个值从JSON对象数组中获取值

jquery: How to Get value from array of JSON Object by another value

本文关键字:对象 数组 获取 JSON 何通过 另一个 jquery      更新时间:2023-09-26

我想通过另一个值从 JSON 对象获取值我的代码:

var ar=[{"one","a"},{"two","b"},{"three","c"},{"four","d"}];

我想在不使用循环的情况下做这样的事情:

var val=ar["c"];   // i want result=three

简单的答案:这是不可能的。循环是只有发布的数据结构时检索的唯一方法。

因此,最好的解决方案是编写一个循环对象并返回值的函数。这样,您就可以在需要时轻松访问它,而无需每次都编写循环。但是,出于显而易见的原因,它是O(n)。

假设上面有拼写错误,并且您打算写:

var ar=[ ["one","a"], ["two","b"] , ["three","c"], ["four","d"] ];

如果您可以使用IE 9及更高版本或其他现代浏览器,array.filter()可以提供帮助:

function findMatch( ar, key ) {
  var matches = ar.filter(
    function( el ) {
      return (el[1] == key);  // match against the second element of each member
    }
  );
  if (matches.length > 0)
    return( matches[0][0] );  // return the first element of the first match
  else 
    return null;
}
var val = findMatch( ar, "c" );

对于早期的浏览器,此处包含 DIY 版本的 filter:https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/filter

假设你实际上有一个数组数组。而且你没有改变它。您可以将此数组转换为对象。

var ar=[ ["one","a"], ["two","b"] , ["three","c"], ["four","d"] ];
var cache = (function(arr){
    var cache = {};
    arr.forEach(function(item){cache[item[1]] = item[0]});
    return cache;
}(ar));
cache["c"]; //"three"

没有循环绝对是可能的,只是不是最好的方法,

假设您的数组按该顺序排列,对象进度为 abc。键是小写的 A 到 Z

var ar=[{"one" : "a"},{"two" : "b"},{"three" : "c"},{"four" : "d"}];
var key = ("c".charCodeAt(0) - 97);
var val = Object.keys(ar[key])[0];

**注意,根据处理此代码的 JS 引擎,您可能会也可能不会得到答案,因为对象中的第一项与人们想象的不一样。我的意思是,对象不是有序

编辑:我忘了修复你的对象,这是jsfiddlehttp://jsfiddle.net/rJ7j9/