组织数组中的元素

时间:2017-05-31 10:18:51

标签: javascript arrays typescript

我正在通过智能方式搜索其中的元素来重新编排数组: 在进入中我得到了:

[{"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;
}

感谢&#39; S

5 个答案:

答案 0 :(得分:1)

您可以使用public void Bind_JumpLists_ItemsSource(ItemsControl control) { db.JumpLists.ToList(); control.DataContext = this; control.ItemsSource = db.JumpLists.Local; control.Tag = db.JumpLists.Local; SelectedJumpList = db.JumpLists.FirstOrDefault(); } 对数组进行分组并映射对象:

dependencies {
    compile files('libs/yourfilename.jar')
}

答案 1 :(得分:0)

还有一种方法:

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

答案 2 :(得分:0)

另一个解决方案,它也处理'id'=&gt; '@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 Set(a.map(({country}) => country))] // list of unique country names
  .map(c => Object.assign({name: c}, // for each country
    {degrees: a.filter(x => x.country === c).map(y => Object.keys(y).includes('id') // handle 'id' => '@id' mutation
      ? {'@id': "/subscription_fields/" + y.id, name: y.name, country: y.country}
      : y)
    }))

console.log(r)

答案 3 :(得分:0)

这纯粹是ES6,非常简洁,但可能性较差。此外,它不会添加“@id”:“/ subscription_fields / 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'));

答案 4 :(得分:0)

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

&#13;
&#13;
var data = [{ name: "brevet", country: "fr" }, { name: "bac", country: "fr" }, { id: 73, name: "des", country: "ca" }, { name: "dep", country: "ca" }, { name: "other", country: "other" }],
    result = data.reduce(function (hash) {
        return function (r, a) {
            if (!hash[a.country]) {
                hash[a.country] = { name: a.country, degrees: [] };
                r.push(hash[a.country]);
            }
            hash[a.country].degrees.push({ name: a.name, country: a.country });
            return r;
        };
    }(Object.create(null)), []);

console.log(result);
&#13;
.as-console-wrapper { max-height: 100% !important; top: 0; }
&#13;
&#13;
&#13;