如何基于对象数组创建新对象

时间:2020-02-26 15:54:28

标签: javascript arrays object

我有一个国家/地区列表对象,我想以合乎逻辑的方式组织它们

abc
abc

abc2
abc2

xyz
xyz

xyz
xyz

这是理想的结果

    const countries = {
        list: [
            {name: 'India', continent: 'Asia'},
            {name: 'China', continent: 'Asia'},
            {name: 'France', continent: 'Europe'},
            {name: 'Germany', continent: 'Europe'},
        ]
    }

我已经使用Set and Spread获取了独特的大陆,但不知道如何前进

    const countriesSorted = {
        list: [
            {Asia: ['India', 'China']},
            {Europe: ['France', 'Germany']}
        ]
    }

6 个答案:

答案 0 :(得分:3)

您可以使用功能reduce对国家进行如下分组:

const countries = {list: [{name: 'India', continent: 'Asia'},{name: 'China', continent: 'Asia'},{name: 'France', continent: 'Europe'},{name: 'Germany', continent: 'Europe'}]},
      countriesSorted = {list: Object.values(countries.list.reduce((a, {name, continent}) => {
            (a[continent] || (a[continent] = {[continent]: []}))[continent].push(name);
            return a;
          }, {}))
      };

console.log(countriesSorted);

没有短路评估速记。

const countries = {list: [{name: 'India', continent: 'Asia'},{name: 'China', continent: 'Asia'},{name: 'France', continent: 'Europe'},{name: 'Germany', continent: 'Europe'}]},
      countriesSorted = {
        list: Object.values(countries.list.reduce((a, {name,continent}) => {
          if (!a[continent]) {
            a[continent] = {
              [continent]: []
            }
          }

          a[continent][continent].push(name);
          return a;
        }, {}))
      };

console.log(countriesSorted);

答案 1 :(得分:0)

希望这会有所帮助,

const countries = {
  list: [{
      name: 'India',
      continent: 'Asia'
    },
    {
      name: 'China',
      continent: 'Asia'
    },
    {
      name: 'France',
      continent: 'Europe'
    },
    {
      name: 'Germany',
      continent: 'Europe'
    },
  ]
}

const out = {};
for (const country of countries.list) {
  if (!Array.isArray(out[country.continent])) out[country.continent] = [];
  out[country.continent].push(country.name);
}

const countriesSorted = {
  list: []
};
for (const key in out) {
  countriesSorted.list.push({
    [key]: out[key]
  });
}

console.log(countriesSorted);

答案 2 :(得分:0)

这是一个潜在的解决方案。我已删除了嵌套列表,因为此示例不需要此嵌套列表。

const list = [
        {name: 'India', continent: 'Asia'},
        {name: 'China', continent: 'Asia'},
        {name: 'France', continent: 'Europe'},
        {name: 'Germany', continent: 'Europe'}
]

//Initialise the object.
let continents = {};

//Initialise the continent with empty array.
list.forEach(el => {
    if (!continents[el.continent]) {
        continents[el.continent] = [];
    }
})

//Push the country name to the correct continent array.
list.forEach(el => {
    continents[el.continent].push(el.name);
})

console.log(continents)

答案 3 :(得分:0)

为清晰起见,需要进行重构,但这是可行的。

const countries = {
   list: [
 {name: 'India', continent: 'Asia'},
 {name: 'China', continent: 'Asia'},
 {name: 'France', continent: 'Europe'},
 {name: 'Germany', continent: 'Europe'},
   ]
}

// Get unique continents
const continents = Array.from(new Set(countries.list.map(c => c.continent)))

const sorted = { 
list: continents.map(c => 
  ({ [c]:  
     countries.list.map(co => 
        co.continent === c ? co.name : undefined)
   .filter(e => !!e) }))}

console.log(sorted)

答案 4 :(得分:0)

我会这样尝试

const countries = {
    list: [
        { name: 'India', continent: 'Asia' },
        { name: 'China', continent: 'Asia' },
        { name: 'France', continent: 'Europe' },
        { name: 'Germany', continent: 'Europe' },
    ]
}

let sortedArr = []

for(let obj of countries.list){
    //If the continent has not been added already add it and assign new set with current country
    if(!sortedArr[obj.continent]) sortedArr[obj.continent] = new Set().add(obj.name)
    else sortedArr[obj.continent].add(obj.name)
}
console.log(sortedArr)

答案 5 :(得分:0)

这可以帮助:

const countries = {
        list: [
            {name: 'India', continent: 'Asia'},
            {name: 'China', continent: 'Asia'},
            {name: 'France', continent: 'Europe'},
            {name: 'Germany', continent: 'Europe'},
        ]
    }
    const continents=[...new Set(countries.list.map(el=>el.continent))];
    var data={}
    continents.forEach(element => {
        data[element]=countries.list.filter(obj=>obj.continent===element).map(item=>item.name)
    });
    const countriesSorted = {
        list:data
    }
    console.log(countriesSorted)