简体   繁体   English

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

[英]How to create a new Object based on an array of objects

I have a countries list object and i want to organise them in a logical manner我有一个国家列表对象,我想以合乎逻辑的方式组织它们

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

This is desired outcome这是想要的结果

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

I have fetched unique continents using Set and Spread but don't know how to go forward我已经使用 Set 和 Spread 获取了独特的大陆,但不知道如何继续

    const continentSet = new Set(countries.list.map(country=>country.continent))

    const continents = [...continentSet]

You can use the function reduce for grouping the countries as follow:您可以使用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);

With no short-circuit evaluation shorthand.没有短路评估速记。

 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);

Hope this will help,希望这会有所帮助,

 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);

Here's a potential solution.这是一个潜在的解决方案。 I have remove the nested list as it wasn't necessary for this example.我已经删除了嵌套列表,因为本示例不需要它。

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)

Needs refactoring for clarity, but it works.为了清晰起见需要重构,但它有效。

 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)

I would try it like this我会像这样尝试

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)

This can help:这可以帮助:

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)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

相关问题 根据对象的 id 创建一个新的对象数组 - Create a new array of object based on the ids of the objects 如何从对象数组创建一个新的 object? - How to create a new object from array of objects? 基于对象的深层嵌套数组创建一个新对象 - create a new object based on deep nested array of objects lodash 比较数组中的对象并基于此比较创建一个新的 object - lodash comparing objects in an array and create a new object based on this comparison 如何根据 object 值从两个 arrays 创建一个新的对象数组? - How to create a new array of objects from two arrays based on object values? 如何根据对象数组的值创建一个新的项目数组? - How to create a new array of items based on the values of an array of objects? 通过基于javascript中每个对象的属性值对对象数组进行分组来创建新的对象数组 - Create new array of objects by grouping array of objects based on property value of each object in javascript 基于对象内部数组的新对象数组? - New array of objects based on an array inside an object? 如何根据属性值合并 2 个对象以创建新的 object? - How to merge 2 objects based on a property value to create new object? 如何根据两个现有 arrays 的值创建新的对象数组? - How to create a new array of objects based on the values of two existing arrays?
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM