过滤和排序对象的嵌套数组

时间:2020-06-09 12:43:42

标签: javascript arrays sorting filter

我有一个对象数组,每个对象都有另一个对象数组,我希望通过特定的键值对其进行过滤-例如,仅返回 name:“ jobs”

在那之后,我想对company数组中的所有对象进行排序,并返回得分最高的“ jobs”对象。

我不确定解决此问题的最佳方法是什么。

这是对象的原始数组:

        companies = [
         {
         about:"Dolore occaecat cillum."
         address:"Manhattan Court, 445"
         city:"Brecon, Massachusetts"
         email:"info@ziggles.info"
         id:0
         name:"Ziggles"
         phone:"+1 (944) 472-2911"
         postal_code:33
         project_number:2016823
         scores:[
           {
             name:"jobs"
             score:"2.7"
           },
           {
             name:"facility"
             score:"4.2"
           },
           {
             name:"location"
             score:"4.7"
           }
         ]
         },
         ...
        ]

我想过滤阵列得分并为公司阵列中的每个对象返回以下结构

        companies = [
         {
         about:"Dolore occaecat cillum."
         address:"Manhattan Court, 445"
         city:"Brecon, Massachusetts"
         email:"info@ziggles.info"
         id:0
         name:"Ziggles"
         phone:"+1 (944) 472-2911"
         postal_code:33
         project_number:2016823
         scores:[
           {
             name:"jobs"
             score:"2.7"
           }
          ]
         },
         ...
        ]

1 个答案:

答案 0 :(得分:0)

您需要先过滤,然后对数组进行排序

// remove extra details of companies to make code easier to read
companies = [
         {
     
         id:0,
 
    
         scores:[
           {
             name:"jobs",
             score:"2.7"
           },
           {
             name:"facility",
             score:"4.2"
           },
           {
             name:"location",
             score:"4.7"
           }
         ],
         },
           {
      
         name:"C2",
    
         scores:[
           {
             name:"jobs",
             score:"3"
           },
           {
             name:"facility",
             score:"4.2"
           },
           {
             name:"location",
             score:"4.7"
           }
         ]
         },
           {
  
         name:"C3",
     
         scores:[
         
           {
             name:"facility",
             score:"4.2"
           },
           {
             name:"location",
             score:"4.7"
           }
         ]
         },
         
        ]
        

 // if companies is a big array you might want to combine filter an
const newCompanies = companies.filter(comp => comp.scores.find(scoreObject => scoreObject.name === 'jobs')).sort((comp1, comp2) =>  parseFloat(comp2.scores.find(scoreObject => scoreObject.name === 'jobs').score, 10) - parseFloat(comp1.scores.find(scoreObject => scoreObject.name === 'jobs').score,10))
console.log(newCompanies) // first element will have highest score