javascript - 如何按名称和列关联对象

标签 javascript arrays javascript-objects

我对以下情况有疑问,所以请检查以下对象数组:

 let arrayQualityRated = [{
     name: "Jande",
     col: 4
 }, {
     name: "Good",
     col: 4
 }, {
     name: "Good",
     col: 4
 }, {
     name: "Bad",
     col: 4
 }, {
     name: "Elmo",
     col: 2
 }, {
     name: "Bad",
     col: 2
 }, {
     name: "Tiago",
     col: 3
 }, {
     name: "Bad",
     col: 3
 }];

我想做一些类似基于 namecol 键的过滤器。

但我需要动态执行,因此根据我的理解,根据以下数组查找键“name”:

let persons = ["Jande", "Elmo", "Tiago"]

我希望我已经澄清了我的疑问。我期待您的耐心和帮助! :)

我期望这样的输出:

[   
    {
        name: "Jande",
        col: 4
    },
    {
        name: "Good",
        col: 4
    },
    {
        name: "Bad",
        col: 4
    },
    {
        name: "Good",
        col: 4
    }

],

[   
    {
        name: "Elmo",
        col: 2
    },
    {
        name: "Bad",
        col: 2
    }

],

[   
    {
        name: "Tiago",
        col: 3
    },
    {
        name: "Bad",
        col: 3
    }

]

简单地说,我想要一个基于字符串“person name”(基于数组“persons”)和“col”的单独对象数组。

最佳答案

我认为这不是一个简单的过滤器,因为结果预计在三个不同的数组中。我会使用 ma​​p() 然后使用 filter(),因为 col 值是动态的(在识别此人之前无法辨别)按名称)。

看看生成的数组 - 它具有您要求的结构。

let arrayQualityRated = [{
  name: "Jande",
  col: 4
}, {
  name: "Good",
  col: 4
}, {
  name: "Good",
  col: 4
}, {
  name: "Bad",
  col: 4
}, {
  name: "Elmo",
  col: 2
}, {
  name: "Bad",
  col: 2
}, {
  name: "Tiago",
  col: 3
}, {
  name: "Bad",
  col: 3
}];

let persons = ["Jande", "Elmo", "Tiago"]

const classifyArrayItems = (persons, arrayQualityRated) => {
  // mapping the array, so it has all the persons
  return persons.map(person => {
    // first find the col number corresponding to the
    // person in the array
    const col = arrayQualityRated.find(e => e.name === person).col
    // return all the objects that have the same
    // col value
    return arrayQualityRated.filter(e => e.col === col)
  })
}

console.log(classifyArrayItems(persons, arrayQualityRated))

关于javascript - 如何按名称和列关联对象,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/57792530/

相关文章:

javascript - 从嵌套的 forEach 循环中的最后一个结果中删除逗号

javascript - 动态加载 JavaScript 库并调用

javascript - 如何从 jQuery 调用 PHP 函数?

javascript - 当我向我的网站注册新用户时,出现此错误“secretOrPrivateKey 必须具有值”! Node.js

python - 在 for 循环中使用相应的 3D numpy 数组

javascript - 返回 firebase 数组返回元组而不是数组

javascript - 如何在 RaphaelJS 中设置文本字体

javascript - 从解析的 CSV 数组中删除重复项

java - 高尔顿箱;打印直方图

javascript - 如何替换嵌套对象中的键