基于数组对象中的另一个值,使用JavaScript获取一个值。

3
我正在尝试从JavaScript对象数组中返回一个值,该数组的第一个对象是:
 dict=[{index:"1",caption:"AAAffterA",blurb:"stuff to write here asieh 1flsidg"}]

我如何根据"A"值返回"B"值(简介)?我的方法很麻烦,但我相信有更简单的方法。
A = "AAAffterA"
var result = dict.map(function(a) {return a.caption;});
key = jQuery.inArray(A,result)
B = dict[key].blurb
4个回答

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
你差不多做到了。不要返回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'

1
这个代码不太行,因为我的数组字典里有多个对象,所以从 dict.map 返回的数组长度大于1,因此 [0] 元素并不总是被填充。如果我去掉 [0],我得到 ,,,,,,,'stuff to write here asieh 1flsidg',,,,,,. - Anton
需要对数组进行额外的筛选.filter(isNotNull),并返回第一个元素。 - aarti

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


-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)

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


网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接