javascript根据对象数组中的另一个获取值

时间:2015-07-03 13:27:19

标签: javascript

我试图从javascript中的对象数组中返回一个值, 数组中的第一个对象是;

 dict=[{index:"1",caption:"AAAffterA",blurb:"stuff to write here asieh 1flsidg"}]

我怎样才能返回" blurb"值(B)如果我有"标题"值(A)? 我设法以looong的方式做到了,但我确信有一种更简单的方法吗?

A = "AAAffterA"
var result = dict.map(function(a) {return a.caption;});
key = jQuery.inArray(A,result)
B = dict[key].blurb

4 个答案:

答案 0 :(得分:1)

只需拨打一个功能。

var dict = [{ index: "1", caption: "AAAffterA", blurb: "stuff to write here asieh 1flsidg" }],
    a = "AAAffterA",
    b = dict.reduce(function (res, el) {
        return el.caption === a ? el.blurb : res;
    }, undefined);
alert(b);

这是多次出现的解决方案:

var dict = [{ index: "1", caption: "AAAffterA", blurb: "stuff to write here asieh 1flsidg" }, { index: "2", caption: "AAAffterA", blurb: "index 2 stuff to write here asieh 1flsidg" }],
    a = "AAAffterA",
    b = dict.reduce(function (res, el) {
        el.caption === a && res.push(el.blurb);
        return res;
    }, []);
alert(JSON.stringify(b));

答案 1 :(得分:1)

你几乎拥有它。

不是返回caption然后再次在dict中查找,而是从地图返回blurb。它会返回这样的东西 ["stuff to write here asieh 1flsidg"]

现在,您可以通过直接从返回的数组中提取第一个结果来减少最后两行。新创建的数组的第一个元素是您要返回的字符串。 ["stuff to write here asieh 1flsidg"][0]只是stuff to write here asieh 1flsidg

> dict=[{index:"1",caption:"AAAffterA",blurb:"stuff to write here asieh 1flsidg"}]
[ { index: '1',
    caption: 'AAAffterA',
    blurb: 'stuff to write here asieh 1flsidg' } ]
> dict.map ( function(a) { if (a.caption == "AAAffterA") return a.blurb } )
[ 'stuff to write here asieh 1flsidg' ]

由于数组可能有多个值,包括nil,filter通过此数组返回非空结果,并使用[0]返回第一个非空结果。

>[ ,,,'stuff to write here asieh 1flsidg' ,,,].filter( function(a) {    
   if (a!=null) return a 
  } ) [0]
    'stuff to write here asieh 1flsidg'

合并为一个最终功能

> dict.map ( function(a) 
 { if (a.caption == "AAAffterA") 
     return a.blurb } 
 ).filter( function(a) { 
    if (a!=null) return a } 
  ) [0]
'stuff to write here asieh 1flsidg'

答案 2 :(得分:0)

首先,过滤数组以仅返回具有所需标题的元素,然后返回该元素(如果已找到):

var A = "AAAffterA",
    dict = [{index:"1",caption:"AAAffterA",blurb:"stuff to write here asieh 1flsidg"}];

// Return all matches for `A`,
var results = dict.filter(function(row){ return row.caption === A; });
// Get the first result, or a error message if none are found.
var found = results.length ? results[0].blurb : "Search returned no results!";

alert(found);

如果找到多行,您可以遍历results

答案 3 :(得分:-1)

你能使用jQuery吗?

如果是,请使用$grep

var dict=[{index:"1",caption:"AAAffterA",blurb:"stuff to write here asieh 1flsidg"}];

var results = $.grep(dict, function(e){ return e.caption == 'AAAffterA'; });

alert(results[0].blurb)

它将返回与数组中的标题匹配的结果数组

相关问题