简体   繁体   中英

Filter array of objects based a nested array of objects

I have an array :

myData: [{
   name: "",
   lastName: "",
   historicalData: [{
    data1: '',
    data2: 0,
   },
    {
    data1: '',
    data2: 30,
   }
  ]
},
{
   name: "",
   lastName: "",
   historicalData: [{
    data1: '',
    data2: 6,
   },
    {
    data1: '',
    data2: 1,
   }
  ]
 }
]

I want to iterate through this array, filter it to have all the data where data2 > 2. And then sort that result by data1.

Since it is a nested array of object within an array of objects, I'm unsure of how to iterate and filter in es6.

Any suggestions ?

myData.filter(oneData => historicalData.data1 > 2)

But initially I would have to map through the historical data too. Expected result:

myData: [{
  name: "",
  lastName: "",
  historicalData: [{
    data1: '',
    data2: 30,
  }]
},{
  name: "",
  lastName: "",
    historicalData: [{
    data1: '',
    data2: 6,
  }]
}]

Once I have this result then I can sort accordingly. THanks

You could build new objects and filter historicalData .

This solution does not mutate the original data.

 var data = [{ name: "", lastName: "", historicalData: [{ data1: '', data2: 0, }, { data1: '', data2: 30, }] }, { name: "", lastName: "", historicalData: [{ data1: '', data2: 6, }, { data1: '', data2: 1, }] }], filtered = data.map(o => Object.assign({}, o, { historicalData: o.historicalData.filter(({ data2 }) => data2 > 2) })); console.log(filtered); 
 .as-console-wrapper { max-height: 100% !important; top: 0; } 

To filter

 myData.map(x => x.historicalData = x.historicalData.filter(x => x.data2 >2))

If you want to sort as well

myData.map(x => x.historicalData = x.historicalData.filter(x => x.data2 >2).sort((y,z)=> y.data1.localeCompare(z.data1) ))

If you want to sort and filter with no mutatation

myData.map( m => { 
  return { 
    ...m , 
    ...{ historicalData: m.historicalData.filter(data  => data.data2 > 2) .sort((y,z)=> y.data1.localeCompare(z.data1))} 
  } 
});

Edit: Added localeCompare, because it's the right way to do string ordering.

 var myData = [{ name: "", lastName: "", historicalData: [{ data1: '', data2: 0, }, { data1: '', data2: 30, }] }, { name: "", lastName: "", historicalData: [{ data1: '', data2: 6, }, { data1: '', data2: 1, }] }]; var res = myData.map( (a) => { a["historicalData"] = a["historicalData"].filter( (aa) => aa["data2"] > 2 ); return a; }); // since you were unclear about the historicalData // array length and how you choose set to 0 res = res.sort( (a,aa) => a["historicalData"][0].data1 - aa["historicalData"][0].data1 ); console.log(res); 

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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