繁体   English   中英

对一个 object 进行排序,其中填充了 arrays 组成的对象

[英]Sort an object which is filled with arrays consisting of objects

我面临一个问题,我得到 Api 结果,为了方便我无法修改,我必须处理我得到的结果。 我得到一个 object ,里面装满了 arrays ,里面也有类似于这个的对象:

{
sectionOne: [{game: 1, order: 3},{game: 2},{game: 3},{game: 4}],                                                       
sectionTwo: [{game: 1, order: 1},{game: 2},{game: 3},{game: 4}],
sectionThree: [{game: 1, order: 2},{game: 2},{game: 3},{game: 4}],
}

在所有部分中,数组中的第一个元素始终有一个名为 order 的键,即 position 数组需要位于 object 中。从上面的示例来看,预期结果应该是:

{
sectionThree: [{game: 1, order 1},{game: 2},{game: 3},{game: 4}],                                                        
sectionOne: [{game: 1, order 2},{game: 2},{game: 3},{game: 4}],
sectionTwo: [{game: 1, order 3},{game: 2},{game: 3},{game: 4}],
}

附言。 我知道没有可以对对象进行排序的方法,我尝试使用条目和键映射它们,但我不知道如何 go 更深入结构并定位它们。

您可以使用Array#sortDestructuring Assignment来做到这一点:

 const obj = { sectionOne: [{ game: 1, order: 3 }, { game: 2 }, { game: 3 }, { game: 4 }], sectionTwo: [{ game: 1, order: 1 }, { game: 2 }, { game: 3 }, { game: 4 }], sectionThree: [{ game: 1, order: 2 }, { game: 2 }, { game: 3 }, { game: 4 }], }; let sortedObj = Object.fromEntries( Object.entries(obj).sort( ([, [{ order: o1 }]], [, [{ order: o2 }]]) => o1 - o2 ) ); console.log(sortedObj);

这对你有用吗?

arr = arr.sort((a, b) => a[0].order - b[0].order)

如果我理解正确的话,你需要 function 这样的:

const sortKeys = (obj) => {
return Object.keys(obj).sort().reduce((acc, key) => {
    acc[key] = obj[key];
    return acc;
}, {});}

暂无
暂无

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

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM