Warning: file_get_contents(/data/phpspider/zhask/data//catemap/9/javascript/424.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Javascript 在数组中组织元素_Javascript_Arrays_Typescript - Fatal编程技术网

Javascript 在数组中组织元素

Javascript 在数组中组织元素,javascript,arrays,typescript,Javascript,Arrays,Typescript,我正在寻找一种通过数组中的元素重新组织数组的智能方法: 在条目中,我有: [{"name": "brevet", "country": "fr" },{ "name": "bac", "country": "fr" },{ "name": "des", "country": "ca" },{ "name": "dep", "country": "ca" }{ "name": "other",, "country": "other"}] 我想按国家/地区重新组织阵列,以便将其包含在输出中: [{

我正在寻找一种通过数组中的元素重新组织数组的智能方法: 在条目中,我有:

[{"name": "brevet",
"country": "fr"
},{
"name": "bac",
"country": "fr"
},{
"name": "des",
"country": "ca"
},{
"name": "dep",
"country": "ca"
}{
"name": "other",,
"country": "other"}]
我想按国家/地区重新组织阵列,以便将其包含在输出中:

[{
    "name": "fr",
    "degrees": [
    {
        "name": "brevet",
        "country": "fr"
    },{
        "name": "bac",
        "country": "fr"
    }]
},{
    "name": "ca",
    "degrees": [{
        "name": "des",
        "country": "ca"
    },{
        "name": "dep",
        "country": "ca"
    }]
},{
    "name": "other",
    "degrees": [{
        "name": "other",
        "country": "other"
    }]
}]
为此,我编写了一个脏函数,但在我看来有更好的方法,但我不知道如何实现。如果有人能用更好的方式来启发我的大脑,我会很有帮助的

private organizeDegrees(degrees: Array<SubscriptionFieldInterface>) {
let degreesByCountry = new Array();
let storeIndex = new Array();
degrees.map(degree => {
  let index = null;
  storeIndex.find((element, idx) => {
    if (element === degree.country) {
      index = idx;
      return true;
    }
  });
  if (index === null) {
    index = degreesByCountry.length;
    let newEntry = {
      'name': degree.country,
      'degrees': new Array()
    };
    storeIndex.push(degree.country);
    degreesByCountry.push(newEntry);
  }
  degreesByCountry[index].degrees.push(degree);
});
return degreesByCountry;
}

thank's

您可以使用object.keys对数组进行分组并映射对象:

还有一个方法:

arr = [ /* your array */ ];

arr = Object.values(arr.reduce((ac, el) => {
    if(!ac[el.country]) ac[el.country] = {"name": el.country, "degrees": []}

    ac[el.country].degrees.push(el);

    return ac
}, {}))

console.log(arr) // formated

另一个解决方案,它还处理“id”=>“@id”映射:

const a=[{name:brevet,country:fr},{name:bac,country:fr},{id:73,name:des,country:ca},{name:dep,country:ca},{name:other,country:other}]; const r=[…new Seta.map{country}=>country]//唯一国家名称列表 .mapc=>Object.assign{name:c},//为每个国家/地区分配 {degrees:a.filterx=>x.country==c.mapy=>Object.keysy.includes'id'//handle'id'=>@id' ?{@id':/subscription_fields/+y.id,名称:y.name,国家:y.country} :y }
logr这纯粹是ES6,非常简洁,但可能可读性较差。此外,它没有添加@id:/subscription\u字段/83,这可以作为后期处理添加:

const groupByKey = (arr, key) => [...arr.reduce((acc, deg) =>
  acc.set(deg[key],  {name: deg[key], degrees: [ ...(acc.get(deg[key]) || {degrees: []}).degrees, deg]})
, new Map()).values()];

console.log(groupByKey(degrees, 'country'));

可以使用哈希表收集对象中的所有值。要获得结果数组,只需推送对象一次

var data=[{name:brevet,country:fr},{name:bac,country:fr},{id:73,name:des,country:ca},{name:dep,country:ca},{name:other,country:other}], 结果=data.reducefunction散列{ 返回函数r,a{ 如果!散列[一个国家]{ hash[a.country]={名称:a.country,学位:[]}; r、 pushhash[一个国家]; } hash[a.country].degrees.push{name:a.name,country:a.country}; 返回r; }; }Object.createnull,[]; console.logresult;
.as控制台包装{max height:100%!important;top:0;}这是较少的排序方式,更多的分组方式。使用Object.valuesObject.values映射更容易。values是非常新的,支持非常有限。感谢您的快速响应。我使用Object.keys的示例是因为我版本的Typescript Object.value不起作用。但我很高兴问这个问题,因为你给了我有用的回答,现在我重新考虑了我所有的脚本。
const groupByKey = (arr, key) => [...arr.reduce((acc, deg) =>
  acc.set(deg[key],  {name: deg[key], degrees: [ ...(acc.get(deg[key]) || {degrees: []}).degrees, deg]})
, new Map()).values()];

console.log(groupByKey(degrees, 'country'));