使用 lodash 访问对象

我正在尝试使用 indexOf 在如下所示的数组中查找键


const areaCode = [

    {

        "area_code": 656,

        "city": "city1"

    },

    {

        "area_code": 220,

        "city": "city2"

    },

    {

        "area_code": 221,

        "city": "city3"

    }]

export default areaCode

然后我试图根据 area_code 号码获取城市名称



const code = input

let found = indexOf(areaCode, ["area_code", code]);

const city = areaCode[found].city

但是发现是-1,我做错了什么?


神不在的星期二
浏览 139回答 3
3回答

哆啦的时光机

你应该使用 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 将保存匹配区域。https://lodash.com/docs/4.17.15#find

慕的地10843

我相信_.findIndex()let found = findIndex(areaCode, ["area_code", code]);

吃鸡游戏

根据文档_.indexOf将执行SameValueZero比较来定位索引。简而言之,因为indexOf(data, item)它会尝试使用===to compareitem与data.相反,您可以使用which accepts将被接受的_.findIndex常用简写:_.matchesProperty_.iterateeconst { findIndex } = _;const areaCode = [    {        "area_code": 656,        "city": "city1"    },    {        "area_code": 220,        "city": "city2"    },    {        "area_code": 221,        "city": "city3"    }]const code = 220;let found = findIndex(areaCode, ["area_code", code]);console.log("index:", found);const city = areaCode[found].cityconsole.log("city:", city);<script src="https://cdn.jsdelivr.net/npm/lodash@4.17.20/lodash.min.js"></script>虽然,鉴于您的用法,您可能想要_.findconst { find } = _;const areaCode = [    {        "area_code": 656,        "city": "city1"    },    {        "area_code": 220,        "city": "city2"    },    {        "area_code": 221,        "city": "city3"    }]const code = 220;let found = find(areaCode, ["area_code", code]);console.log("index:", found);const city = found.cityconsole.log("city:", city);<script src="https://cdn.jsdelivr.net/npm/lodash@4.17.20/lodash.min.js"></script>
打开App,查看更多内容
随时随地看视频慕课网APP

相关分类

JavaScript