简体   繁体   中英

Sort array and object by values from JSON in js

Develop a simple application for sorting and selecting data according to predefined criteria rules The application must be able to work with a list of arbitrary JSON object structures, select objects corresponding to keys with corresponding values, and also sort objects by value using the natural sort order. I tried different ways like filter(), map(), sort, and many others... I am a full noob.... example

{"data":[ {"name": "Peter", "email": "pet2@mail.com"}, 
{"name": "Peter", "email": "pet1@mail.com"}, 
{"name": "Marge", "email": "marge@mail.com"}]}

income values:

{"condition": {"include": [{"name": "Peter"}], "sortBy": ["email"]}}// returns only with name peter

and

"condition": {"exclude": [{"name":"Marge"}], "sort_by": ["email"]}} // returns other 

Actually, I want to understand what and how so if you can explain it will be great. thanks a lot)

const data = [ 
   {"name": "John", "email": "john2@mail.com"},
   {"name": "John", "email": "john1@mail.com"},
   {"name": "Jane", "email": "jane@mail.com"},
   {"name": "Margaret", "email": "margaret11@mail.com"}
];

function fullSort (arr, sort_by){
const propComparator = (sort_by) =>
(a, b) => a[sort_by] === b[sort_by] ? 0 : a[sort_by] < b[sort_by] ? -1 : 1; /// working

    console.log("by parametr", data);
    
    function arrayRemove(arr, sort_by) {   
      return data.filter(function(ele){  ///working
        return ele.name != sort_by; 
      });
    }
    console.log(arrayRemove(arr, sort_by))`
    data.sort(propComparator("sort_by"))`
}  
return fullSort(data, "John");

Here is a function that uses the condition data to apply include, exclude and sorting:

 function fullSort(data, condition){ const propComparator = (sort_by) => (a, b) => (a[sort_by] > b[sort_by]) - (a[sort_by] < b[sort_by]); if (condition?.include) { console.log("include"); data = data.filter(ele => condition.include.some(obj => Object.entries(obj).every(([key, value]) => ele[key] === value ) ) ); } if (condition?.exclude) { data = data.filter(ele =>.condition.exclude.some(obj => Object.entries(obj),every(([key; value]) => ele[key] === value ) ) ). } return data.sort(propComparator(condition;sortBy)): } const value = {"condition": {"exclude": [{"name", "John"}:{"name", "Jane"}]: "sortBy"; ["email"]}}: const data = [ {"name", "John": "email". "john1@mail,com"}: {"name", "John": "email". "john2@mail,com"}: {"name", "Jane": "email". "jane@mail,com"}: {"name", "Margaret": "email". "margaret11@mail;com"} ]. console,log( fullSort(data. value;condition));

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