我正在尝试几种方法来对abjects json数组进行分组,但是我做不到,这是初始数组:
{_id: "455", name: "ALBACETE"}
{_id: "455", name: "ALLICANTE"}
{zone: {_id: "zone1", name: "zone1"}, _id: "143", name: "ALCALA"}
{zone: {_id: "zone1", name: "zone1"}, _id: "144", name: "OTRO"}
{zone: {_id: "zone2", name: "zone2"}, _id: "144", name: "OTRO MAS"}
也就是说,数组中的某些元素没有区域,其他则没有。
我希望得到这样的结果:
{_id: "455", name: "ALBACETE"}
{_id: "455", name: "ALLICANTE"}
{zone: {_id: "zone1", name: "zone1"}, _id: "144", name: "OTRO"}
{zone: {_id: "zone2", name: "zone2"}, _id: "144", name: "OTRO MAS"}
也就是说,它按区域分组(不重复区域1)。
请有人帮助我!尝试许多我做不到的方法。
我尝试:
const q = [
{ zone: { _id: "zone1", name: "zone1" }, _id: "143", name: "ALCALA" },
{ zone: { _id: "zone1", name: "zone1" }, _id: "144", name: "OTRO" },
{ zone: { _id: "zone2", name: "zone2" }, _id: "144", name: "OTRO MAS" },
{ _id: "455", name: "ALBACETE" }
{_id: "455", name: "ALLICANTE"}
];``
let ret = [];
let result = q.filter( x => {
if(!ret.includes(x._id)) {
ret.push(x._id);
return true;
}
return false;
});
But the output does not filter by the object "zone":
[
{ zone: { _id: 'zone1', name: 'zone1' }, _id: '143', name: 'ALCALA' },
{ zone: { _id: 'zone1', name: 'zone1' }, _id: '144', name: 'OTRO' },
{ _id: '455', name: 'ALBACETE' }
答案 0 :(得分:0)
好的,我已经设法通过这种方式解决问题:
forEach
遍历数组,JSON.stringify()
比较值。