“JS JSON Groupby Prop” Kode Jawaban

JavaScript Group dengan Array Properti Objek

function groupArrayOfObjects(list, key) {
  return list.reduce(function(rv, x) {
    (rv[x[key]] = rv[x[key]] || []).push(x);
    return rv;
  }, {});
};

var people = [
    {sex:"Male", name:"Jeff"},
    {sex:"Female", name:"Megan"},
    {sex:"Male", name:"Taylor"},
    {sex:"Female", name:"Madison"}
];
var groupedPeople=groupArrayOfObjects(people,"sex");
console.log(groupedPeople.Male);//will be the Males 
console.log(groupedPeople.Female);//will be the Females
Grepper

JS JSON Groupby Prop

var myJsonFromSQL = [{id:1, cat:'test1'},{id:2, cat:'test1'},
                     {id:3, cat:'test2'},{id:4, cat:'test2'}];

// 1 LINE CODE:
//'Set' deletes/do not consider duplicates
const arr_cat =  [...new Set(myJsonFromSQL.map(i => i.cat))];
//RESULT:
You will get an array with the property values grouped:
arr_cat   ['test1','test2']
Enrybi

Jawaban yang mirip dengan “JS JSON Groupby Prop”

Pertanyaan yang mirip dengan “JS JSON Groupby Prop”

Lebih banyak jawaban terkait untuk “JS JSON Groupby Prop” di JavaScript

Jelajahi jawaban kode populer menurut bahasa

Jelajahi bahasa kode lainnya