我有一个数组,我使用_groupBy将它们分组在类别ID上,并得到如下数组。
{
"cat1":[
{"id":"1","name":"SomeName", "category":"cat1"},
{"id":"15","name":"SomeName2", "category":"cat1"}
],
"cat2":[
{"id":"12","name":"Somename3", "category":"cat2"}
],
"cat3":[
{"id":"18","name":"SomeName4", "category":"cat3"}
]
}
如何检查将其分组的主要组。因此,我可以先渲染cat2,然后再渲染其他类别。
答案 0 :(得分:0)
Object.keys()
返回对象的所有可枚举键。
您还可以使用Object.entries()
,它为您提供一个数组,其中每个项目都是给定对象的[key, value]
。
const data = {
"cat1":[
{"id":"1","name":"SomeName", "category":"cat1"},
{"id":"15","name":"SomeName2", "category":"cat1"}
],
"cat2":[
{"id":"12","name":"Somename3", "category":"cat2"}
],
"cat3":[
{"id":"18","name":"SomeName4", "category":"cat3"}
]
}
const delayed = [];
for(const [name, value] of Object.entries(data)) {
if (name === "cat2") {
console.log(value); // first log cat2
continue;
}
delayed.push(value); // the rest will be put to delayed array
}
delayed.forEach(console.log.bind(console)); // log remaining items
另一种方法是使用对象分解来从对象中拔出cat2
,先使用它,然后对其余对象进行任何操作:
const { cat2, ...rest } = obj;