简体   繁体   English

Lodash for 循环在使用“i”时返回未定义,但适用于设置值

[英]Lodash for loop returns undefined upon using the “i”, but works with set values

I'm trying to search an object for certain integer values using Lodash and then push some of the object values into an array.我正在尝试使用 Lodash 在 object 中搜索某些 integer 值,然后将一些 object 值推送到数组中。 The integer values have to be variable and come from a different array, but always returns an undefined value integer 值必须是可变的并且来自不同的数组,但始终返回未定义的值

When I hardcode the value like this: _.find(getChampionList.data, { 'key': '266'}) it works perfectly, however if I use a variable from my array it returns undefined.当我对这样的值进行硬编码时: _.find(getChampionList.data, { 'key': '266'})它可以完美运行,但是如果我使用数组中的变量,它会返回未定义。

The object I'm trying to extract data from:我试图从 object 中提取数据:

var getChampionList = {
    "type": "champion",
    "format": "standAloneComplex",
    "version": "9.18.1",
    "data": {
        "Aatrox": {
            "version": "9.18.1",
            "id": "Aatrox",
            "key": "266",
            "name": "Aatrox",
            "title": "the Darkin Blade",
            "blurb": "Once honored defenders of Shurima against the Void, Aatrox and his brethren would eventually become an even greater threat to Runeterra, and were defeated only by cunning mortal sorcery. But after centuries of imprisonment, Aatrox was the first to find...",
            "info": {
                "attack": 8,
                "defense": 4,
                "magic": 3,
                "difficulty": 4
            },
            "image": {
                "full": "Aatrox.png",
                "sprite": "champion0.png",
                "group": "champion",
                "x": 0,
                "y": 0,
                "w": 48,
                "h": 48
            },
            "tags": [
                "Fighter",
                "Tank"
            ],
            "partype": "Blood Well",
            "stats": {
                "hp": 580,
                "hpperlevel": 90,
                "mp": 0,
                "mpperlevel": 0,
                "movespeed": 345,
                "armor": 38,
                "armorperlevel": 3.25,
                "spellblock": 32.1,
                "spellblockperlevel": 1.25,
                "attackrange": 175,
                "hpregen": 3,
                "hpregenperlevel": 1,
                "mpregen": 0,
                "mpregenperlevel": 0,
                "crit": 0,
                "critperlevel": 0,
                "attackdamage": 60,
                "attackdamageperlevel": 5,
                "attackspeedperlevel": 2.5,
                "attackspeed": 0.651
            }
        },
        "Ahri": {
            "version": "9.18.1",
            "id": "Ahri",
            "key": "103",
            "name": "Ahri",
            "title": "the Nine-Tailed Fox",
            "blurb": "Innately connected to the latent power of Runeterra, Ahri is a vastaya who can reshape magic into orbs of raw energy. She revels in toying with her prey by manipulating their emotions before devouring their life essence. Despite her predatory nature...",
            "info": {
                "attack": 3,
                "defense": 4,
                "magic": 8,
                "difficulty": 5
            },
            "image": {
                "full": "Ahri.png",
                "sprite": "champion0.png",
                "group": "champion",
                "x": 48,
                "y": 0,
                "w": 48,
                "h": 48
            },
            "tags": [
                "Mage",
                "Assassin"
            ],
            "partype": "Mana",
            "stats": {
                "hp": 526,
                "hpperlevel": 92,
                "mp": 418,
                "mpperlevel": 25,
                "movespeed": 330,
                "armor": 20.88,
                "armorperlevel": 3.5,
                "spellblock": 30,
                "spellblockperlevel": 0.5,
                "attackrange": 550,
                "hpregen": 6.5,
                "hpregenperlevel": 0.6,
                "mpregen": 8,
                "mpregenperlevel": 0.8,
                "crit": 0,
                "critperlevel": 0,
                "attackdamage": 53.04,
                "attackdamageperlevel": 3,
                "attackspeedperlevel": 2,
                "attackspeed": 0.668
            }
        }
    }
}

var championIds = [ 266, 103 ]

    for (i = 0; i < championIds.length; i++) {
         var champion = _.find(getChampionList.data, { 'key': championIds[i]})
         console.log(champion) //returns undefined
         championArray.push(champion.id) //creates an error
      }

The line var champion = _.find(getChampionList.data, { 'key': championIds[i]}) should return the objects and then push the "id" field into "championArray". var champion = _.find(getChampionList.data, { 'key': championIds[i]})行应该返回对象,然后将“id”字段推入“championArray”。 Hardcoded like this { 'key': '266'} it returns the object for Aatrox, but with the championIds[i] it just gives an undefined value (while championIds[0] does return "266").像这样的硬编码{ 'key': '266'}它返回 Aatrox 的 object,但使用 ChampionIds championIds[i]它只是给出一个未定义的值(而 ChampionIds[0] 确实返回“266”)。

I'm not sure what's wrong with my code, but perhaps it has to do with Lodash or a typing mistake?我不确定我的代码有什么问题,但可能与 Lodash 或打字错误有关? I've been looking at it for hours console.logging every line, but can't see what's wrong.我已经看了好几个小时 console.logging 每一行,但看不出有什么问题。

You will need to do three things:你需要做三件事:

  1. Since you "know" you need to locate the key values, start with championData.data既然你“知道”你需要找到key值,那就从championData.data开始
  2. Reduce objects (key-value pairs) to a list将对象(键值对)简化为列表
  3. Parse the key as an integer将密钥解析为 integer

Alternatively, you could map and filter.或者,您可以使用 map 和过滤器。

 let championData = getData(), championIds = [ 266, 103 ], championList = Object.keys(championData.data).reduce((list, name) => { return championIds.includes(parseInt(championData.data[name].key, 10))? list.concat(championData.data[name].id): list; }, []); console.log(championList); function getData() { return { "type": "champion", "format": "standAloneComplex", "version": "9.18.1", "data": { "Aatrox": { "version": "9.18.1", "id": "Aatrox", "key": "266", "name": "Aatrox", "title": "the Darkin Blade", "blurb": "Once honored defenders of Shurima against the Void, Aatrox and his brethren would eventually become an even greater threat to Runeterra, and were defeated only by cunning mortal sorcery. But after centuries of imprisonment, Aatrox was the first to find...", "info": { "attack": 8, "defense": 4, "magic": 3, "difficulty": 4 }, "image": { "full": "Aatrox.png", "sprite": "champion0.png", "group": "champion", "x": 0, "y": 0, "w": 48, "h": 48 }, "tags": [ "Fighter", "Tank" ], "partype": "Blood Well", "stats": { "hp": 580, "hpperlevel": 90, "mp": 0, "mpperlevel": 0, "movespeed": 345, "armor": 38, "armorperlevel": 3.25, "spellblock": 32.1, "spellblockperlevel": 1.25, "attackrange": 175, "hpregen": 3, "hpregenperlevel": 1, "mpregen": 0, "mpregenperlevel": 0, "crit": 0, "critperlevel": 0, "attackdamage": 60, "attackdamageperlevel": 5, "attackspeedperlevel": 2.5, "attackspeed": 0.651 } }, "Ahri": { "version": "9.18.1", "id": "Ahri", "key": "103", "name": "Ahri", "title": "the Nine-Tailed Fox", "blurb": "Innately connected to the latent power of Runeterra, Ahri is a vastaya who can reshape magic into orbs of raw energy. She revels in toying with her prey by manipulating their emotions before devouring their life essence. Despite her predatory nature...", "info": { "attack": 3, "defense": 4, "magic": 8, "difficulty": 5 }, "image": { "full": "Ahri.png", "sprite": "champion0.png", "group": "champion", "x": 48, "y": 0, "w": 48, "h": 48 }, "tags": [ "Mage", "Assassin" ], "partype": "Mana", "stats": { "hp": 526, "hpperlevel": 92, "mp": 418, "mpperlevel": 25, "movespeed": 330, "armor": 20.88, "armorperlevel": 3.5, "spellblock": 30, "spellblockperlevel": 0.5, "attackrange": 550, "hpregen": 6.5, "hpregenperlevel": 0.6, "mpregen": 8, "mpregenperlevel": 0.8, "crit": 0, "critperlevel": 0, "attackdamage": 53.04, "attackdamageperlevel": 3, "attackspeedperlevel": 2, "attackspeed": 0.668 } } } }; }
 .as-console-wrapper { top: 0; max-height: 100%;important; }

You use _.find() correctly.您正确使用_.find() Find doesn't work because the keys are strings, and you're looking for numbers: Find 不起作用,因为键是字符串,而您正在寻找数字:

 var getChampionList = {"type":"champion","format":"standAloneComplex","version":"9.18.1","data":{"Aatrox":{"version":"9.18.1","id":"Aatrox","key":"266","name":"Aatrox","title":"the Darkin Blade","blurb":"Once honored defenders of Shurima against the Void, Aatrox and his brethren would eventually become an even greater threat to Runeterra, and were defeated only by cunning mortal sorcery. But after centuries of imprisonment, Aatrox was the first to find...","info":{"attack":8,"defense":4,"magic":3,"difficulty":4},"image":{"full":"Aatrox.png","sprite":"champion0.png","group":"champion","x":0,"y":0,"w":48,"h":48},"tags":["Fighter","Tank"],"partype":"Blood Well","stats":{"hp":580,"hpperlevel":90,"mp":0,"mpperlevel":0,"movespeed":345,"armor":38,"armorperlevel":3.25,"spellblock":32.1,"spellblockperlevel":1.25,"attackrange":175,"hpregen":3,"hpregenperlevel":1,"mpregen":0,"mpregenperlevel":0,"crit":0,"critperlevel":0,"attackdamage":60,"attackdamageperlevel":5,"attackspeedperlevel":2.5,"attackspeed":0.651}},"Ahri":{"version":"9.18.1","id":"Ahri","key":"103","name":"Ahri","title":"the Nine-Tailed Fox","blurb":"Innately connected to the latent power of Runeterra, Ahri is a vastaya who can reshape magic into orbs of raw energy. She revels in toying with her prey by manipulating their emotions before devouring their life essence. Despite her predatory nature...","info":{"attack":3,"defense":4,"magic":8,"difficulty":5},"image":{"full":"Ahri.png","sprite":"champion0.png","group":"champion","x":48,"y":0,"w":48,"h":48},"tags":["Mage","Assassin"],"partype":"Mana","stats":{"hp":526,"hpperlevel":92,"mp":418,"mpperlevel":25,"movespeed":330,"armor":20.88,"armorperlevel":3.5,"spellblock":30,"spellblockperlevel":0.5,"attackrange":550,"hpregen":6.5,"hpregenperlevel":0.6,"mpregen":8,"mpregenperlevel":0.8,"crit":0,"critperlevel":0,"attackdamage":53.04,"attackdamageperlevel":3,"attackspeedperlevel":2,"attackspeed":0.668}}}} var championIds = [266, 103] var championArray = [] for (i = 0; i < championIds.length; i++) { var champion = _.find(getChampionList.data, { 'key': String(championIds[i]) // convert the championIds[i] to String }) championArray.push(champion.id) } console.log(championArray)
 <script src="https://cdnjs.cloudflare.com/ajax/libs/lodash.js/4.17.15/lodash.js"></script>

However, this is it not really efficient, since each search loop starts from the beginning.然而,这并不是很有效,因为每个搜索循环都是从头开始的。 If you've got a short data collection, you want see any difference.如果您有一个简短的data收集,您希望看到任何差异。 However, for long data , you can use _.intersectionWith() to find the items with the relevant keys, and then use _.map() to extract the id values.但是,对于长data ,您可以使用_.intersectionWith()查找具有相关键的项目,然后使用_.map()提取id值。

 var getChampionList = {"type":"champion","format":"standAloneComplex","version":"9.18.1","data":{"Aatrox":{"version":"9.18.1","id":"Aatrox","key":"266","name":"Aatrox","title":"the Darkin Blade","blurb":"Once honored defenders of Shurima against the Void, Aatrox and his brethren would eventually become an even greater threat to Runeterra, and were defeated only by cunning mortal sorcery. But after centuries of imprisonment, Aatrox was the first to find...","info":{"attack":8,"defense":4,"magic":3,"difficulty":4},"image":{"full":"Aatrox.png","sprite":"champion0.png","group":"champion","x":0,"y":0,"w":48,"h":48},"tags":["Fighter","Tank"],"partype":"Blood Well","stats":{"hp":580,"hpperlevel":90,"mp":0,"mpperlevel":0,"movespeed":345,"armor":38,"armorperlevel":3.25,"spellblock":32.1,"spellblockperlevel":1.25,"attackrange":175,"hpregen":3,"hpregenperlevel":1,"mpregen":0,"mpregenperlevel":0,"crit":0,"critperlevel":0,"attackdamage":60,"attackdamageperlevel":5,"attackspeedperlevel":2.5,"attackspeed":0.651}},"Ahri":{"version":"9.18.1","id":"Ahri","key":"103","name":"Ahri","title":"the Nine-Tailed Fox","blurb":"Innately connected to the latent power of Runeterra, Ahri is a vastaya who can reshape magic into orbs of raw energy. She revels in toying with her prey by manipulating their emotions before devouring their life essence. Despite her predatory nature...","info":{"attack":3,"defense":4,"magic":8,"difficulty":5},"image":{"full":"Ahri.png","sprite":"champion0.png","group":"champion","x":48,"y":0,"w":48,"h":48},"tags":["Mage","Assassin"],"partype":"Mana","stats":{"hp":526,"hpperlevel":92,"mp":418,"mpperlevel":25,"movespeed":330,"armor":20.88,"armorperlevel":3.5,"spellblock":30,"spellblockperlevel":0.5,"attackrange":550,"hpregen":6.5,"hpregenperlevel":0.6,"mpregen":8,"mpregenperlevel":0.8,"crit":0,"critperlevel":0,"attackdamage":53.04,"attackdamageperlevel":3,"attackspeedperlevel":2,"attackspeed":0.668}}}} var championIds = [266, 103] var championArray = _.map( _.intersectionWith( _.values(getChampionList.data), // get an array of data items championIds, (a, b) => a.key == b // use loose equality that ignores the type ), 'id') // extract the id using map console.log(championArray)
 <script src="https://cdnjs.cloudflare.com/ajax/libs/lodash.js/4.17.15/lodash.js"></script>

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM