2013-09-25 45 views
0

我有:stackoverflow.com/questions/19012903/get-value-from-multi-object 但我修改了这一点,我想添加到结果字符串超过4个字符。地图,过滤器和自己的值

function isLong(val) 
{ 
    if(val.length > 4){ 
     return true; 
    } else { 
     return false; 
    } 
} 

var page = [{ 
    title: 'aaa', 
    text: '111' 
}, { 
    title: 'bbb', 
    text: '222' 
}, { 
    title: 'ccc', 
    text: '333' 
}, { 
    title: 'ddd', 
    text: '444' 
}, { 
    title: 'eee', 
    text: '444' 
}]; 

console.log([].concat.apply([], '222, 333, 4441, long1, long, long2'.split(', ').map(function (t) { 
    return page.filter(function (o) { 
     return o.text === t || isLong(t); 
    }).map(function (c) { 
     return c.title 
    }); 
})).join(", ")); 

jsfiddle

但是这回我的所有值。我试着检查这一行return o.text === t || isLong(T);

对于这个例子我想接收:

BBB,CCC,long1,long2

BBB和CCC从对象页面。 long1和long2是由逗号分隔的自定义字符串。

+0

过滤器返回一个数组,这始终是trueish – dandavis

+0

所以我怎样才能使它? – claudio3949

回答

1
var str = '222, 333, 4441, long1, long, long2'; 

var strArray = str.split(', '); 

var result = strArray.map(function(s){ 
    return isLong(s) ? s : page.filter(function(o){ // if word has > 4 chars return word else try to match with page array 
     return o.text == s; 
    }).map(function(c){ 
     return c.title; // if matched return title 
    })[0]; // select first match 
}).filter(function(u){ 
    return u; // remove undefined results 
}); 

console.log(result); 

实施例:http://jsfiddle.net/YrZNq/6/