Home > Enterprise >  Reactjs: How to get values from array of objects
Reactjs: How to get values from array of objects

Time:08-12

I am a beginner in rectjs. In my project, there is a list of objects stored in "groupedItems", and using sort() to order them and stored them into a variable "numAscending".

enter image description here

Now its structure is in the above picture. but I want to change them like in the below picture.

enter image description here

Here is the code which I tried.

 groupedItems.map((items)=>{
                numAscending = [...items].sort((a, b) => a.subsolution_name - b.subsolution_name);
                temp.push({numAscending})
            })
            console.log("temp", temp)


            // result = temp.map((option, key) => {
            //     console.log("eeeeeeee", option)
            //     option.map((item)=>{
            //         console.log("iteee", item)
            //     })
            // });

            // console.log('result', result);
            

I tried to fix it but failed (lines are started with //). Please give me a suggestion to solve this problem.

CodePudding user response:

You probably could flatten the groupedItems array's element values, which appear to be arrays, and then sort the overall result array.

Example:

const result = groupedItems
  .flat(Number.POSITIVE_INFINITY)
  .sort((a, b) => a.subsolution_name - b.subsolution_name);

CodePudding user response:

You can reduce it to get the array and then sort it

const reducedItems = groupedItems.reduce((prev,curr)=>{
    return [...prev,...curr.numAscending]
},[]);
const sortedItems = reducedItems.sort((a, b) => a.subsolution_name - b.subsolution_name);
  • Related