Javascript 使用lodash访问对象

Javascript 使用lodash访问对象,javascript,lodash,Javascript,Lodash,我试图使用indexOf在数组中查找一个键,如下所示 const areaCode = [ { "area_code": 656, "city": "city1" }, { "area_code": 220, "city": "city2" }, { &quo

我试图使用indexOf在数组中查找一个键,如下所示

const areaCode = [
    {
        "area_code": 656,
        "city": "city1"
    },
    {
        "area_code": 220,
        "city": "city2"
    },
    {
        "area_code": 221,
        "city": "city3"
    }]
export default areaCode
然后我试着根据区号得到城市名称


const code = input
let found = indexOf(areaCode, ["area_code", code]);
const city = areaCode[found].city

但是,find的结果是-1,我做错了什么?

我相信
\uu。findIndex()
就是您需要的:


下面是一个演示

您应该使用Lodash.find函数

应该是这样的:

const areaCode = [
{
    "area_code": 656,
    "city": "city1"
},
{
    "area_code": 220,
    "city": "city2"
},
{
    "area_code": 221,
    "city": "city3"
}]
const code = input;
const found = _.find(areaCode, function(a){ return a.area_code == code });
console.log(found.city)
const found将保留匹配区域


根据文档,将执行比较以定位索引。简言之,对于
indexOf(data,item)
,它将尝试使用
==
item
数据中的每个条目进行比较

相反,您可以使用以下内容接受的常用速记:

const{findIndex}=\;
警察区号=[
{
“区号”:656,
“城市”:“城市1”
},
{
“区号”:220,
“城市”:“城市2”
},
{
“区号”:221,
“城市”:“城市3”
}]
常数代码=220;
let found=findIndex(区号,[“区号”,代码]);
日志(“索引:”,已找到);
const city=区域代码[found]。城市
控制台日志(“城市:”,城市)

代码的值是多少?它是一个有效的区号!与上面示例中的656或221类似,实际上,
indexOf
不使用
iteratee
进行搜索-它执行相同的值零比较。使用它而不仅仅是查找
有什么特别的原因吗?
const areaCode = [
{
    "area_code": 656,
    "city": "city1"
},
{
    "area_code": 220,
    "city": "city2"
},
{
    "area_code": 221,
    "city": "city3"
}]
const code = input;
const found = _.find(areaCode, function(a){ return a.area_code == code });
console.log(found.city)