我有一个包含词典的数组。像这样:
[{date:1991, value: 78}, {date:1992, value: 102}, {date:1993, value: 277}]
使用日期搜索对象的好方法是:1991并返回值?
答案 0 :(得分:1)
您可以使用Array#find
方法。
var data = [{
date: 1991,
value: 78
}, {
date: 1992,
value: 102
}, {
date: 1993,
value: 277
}],
date = 1991;
console.log(
(data.find(function(v) {
return v.date == date;
}) || {}).value
)
对于较旧的浏览器,请检查polyfill option of find method。
答案 1 :(得分:1)
使用filter()
方法,您可以将其作为
const dict = [ {date:1991, value: 78},
{date:1992, value: 102},
{date:1993, value: 277} ]
console.log(dict.filter(obj => obj.date === 1991))
如果您想在简单的for
和if
循环中回答,您也可以使用用户定义的函数执行相同的操作。
var dict = [{date:1991, value: 78}, {date:1992, value: 102}, {date:1993, value: 277}]
function search_obj(dict, year) {
for (obj of dict) {
if (obj.date === year) {
return obj
}
}
}
console.log(search_obj(dict, 1991))
答案 2 :(得分:1)
创建自己的搜索功能。
var arr = [{date:1991, value: 78}, {date:1992, value: 102}, {date:1993, value: 277}];
function searchFn(searchDate){
for(var i = 0; i < arr.length; i++)
if(arr[i] == searchDate)
return arr[i];
}
//search
searchFn(1991);//{date:1991, value: 78}
searchFn(1992);//{date:1992, value: 102}
答案 3 :(得分:0)
只需使用forEach方法。
var arr=[{date:1991, value: 78}, {date:1992, value: 102}, {date:1993, value: 277},{date:1991, value: 79}];
var v=1991,ans=[];
arr.forEach(function(a){
if(a.date==v)
ans.push(a.value);
});
console.log(ans);
&#13;
答案 4 :(得分:0)
使用简单的过滤语句:
var data = [{date:1991, value: 78}, {date:1992, value: 102}, {date:1993, value: 277}]
var result = data.filter(x => x.date == 1991)
console.log(result)