代码之家  ›  专栏  ›  技术社区  ›  Sergino

对类型脚本字典有问题

  •  1
  • Sergino  · 技术社区  · 7 年前

    我正在建立一个这样的typescirpt字典:

    const skills = x
            .map(y => y.skills)
            .flat(1)
            .map(z => {
              return { [z.id]: { skill: z } };
            });
    

    这就是我通过上面的代码得到的数组:

    { 7ff2c668-0e86-418a-a962-4958262ee337: {skill: {…}} }
    { c6846331-2e11-45d6-ab8d-306c956332fc: {skill: {…}} }
    { 0fc0cb61-f44d-4fd0-afd1-18506380b55e: {skill: {…}} }
    { 36dc0b74-84ee-4be2-a91c-0a91b4576a21: {skill: {…}} }
    

    现在的问题是我无法按键访问词典:

    const id = '7ff2c668-0e86-418a-a962-4958262ee337';
    const one = myArr.find(x => x === id); // returns undefined
    const two = myArr[id]; // returns undefined
    

    有什么办法吗?

    3 回复  |  直到 7 年前
        1
  •  1
  •   Nick Parsons Felix Kling    7 年前

    你可以用 Object.keys() x (您搜索id)。

    请参见下面的示例:

    const myArr = [
    {"7ff2c668-0e86-418a-a962-4958262ee337": {skill: 1}},
    {"c6846331-2e11-45d6-ab8d-306c956332fc": {skill: 2}},
    {"0fc0cb61-f44d-4fd0-afd1-18506380b55e": {skill: 3}},
    {"36dc0b74-84ee-4be2-a91c-0a91b4576a21": {skill: 4}}],
    
    id = "36dc0b74-84ee-4be2-a91c-0a91b4576a21",
    one = myArr.findIndex(x => Object.keys(x)[0] === id); // the index of the object which has the search id as its key.
    
    myArr[one] = {newKey: "newValue"}; // set the index found to have a new object
    console.log(myArr);
        2
  •  1
  •   klugjo    7 年前

    例子:

    const skills = x
        .map(y => y.skills)
        .flat(1)
        .reduce((acc, z) => {
            acc[z.id] = z;
            return acc;
        }, {});
    

    myArr 看起来像是:

    {
        '7ff2c668-0e86-418a-a962-4958262ee337': {...}
        'c6846331-2e11-45d6-ab8d-306c956332fc': {...},
        '0fc0cb61-f44d-4fd0-afd1-18506380b55e': {...},
        '36dc0b74-84ee-4be2-a91c-0a91b4576a21': {...}
    }
    

    然后您可以按预期方式访问它:

    const skill = myArr['7ff2c668-0e86-418a-a962-4958262ee337'];
    
        3
  •  1
  •   Pranay Rana    7 年前

    Map 是ES6中引入的一种新的数据结构。它允许您存储与其他编程语言类似的键值对,例如Java、C#。

    let map = new Map();
    const skills = x
            .map(y => y.skills)
            .flat(1)
            .map(z => {
              map.set(z.Id,  { skill: z })
              return  map;
            });
    
    //Get entries
    amp.get("7ff2c668-0e86-418a-a962-4958262ee337");     //40
    
    //Check entry is present or not
    map.has("7ff2c668-0e86-418a-a962-4958262ee337");       //true