如何在react native中从旧数组获得新数组?



React Native//我有一个这样的数组。如何从我需要使用的旧数组中获得新数组?

data = [
{ id: 1, name: 'Mike Mii', city: 'philps', state: 'New York'},
{ id: 2, name: 'Steve Jav', city: 'Square', state: 'Chicago'},
{ id: 3, name: 'Jhonny', city: 'market', state: 'New York'},
{ id: 4, name: 'philps', city: 'booket', state: 'Texas'},
{ id: 5, name: 'smith', city: 'brookfield', state: 'Florida'},
{ id: 6, name: 'Broom', city: 'old street', state: 'Florida'},
];

我想要得到这样的数组中的数组。字段state相同,应该只显示一个。

new_data = [
{
id: 1, 
state: 'New York',
people: [ 
{
id: 1,
name: 'Mike Mii',
city: 'philps',
},
{
id: 2,
name: 'Jhonny',
city: 'market',
}
]
},
{
id: 2, 
state: 'Florida',
people: [ 
{
id: 1,
name: 'smith',
city: 'brookfield',
},
{
id: 2,
name: 'Broom',
city: 'old street',
}
]
},
{
id: 3, 
state: 'Chicago',
people: [ 
{
id: 1,
name: 'Steve Jav',
city: 'Square',
}
]
},
{
id: 4, 
state: 'Texas',
people: [ 
{
id: 1,
name: 'philps',
city: 'booket',
}
]
}
];

应该这样做。

const data = [
{ id: 1, name: 'Mike Mii', city: 'philps', state: 'New York' },
{ id: 2, name: 'Steve Jav', city: 'Square', state: 'Chicago' },
{ id: 3, name: 'Jhonny', city: 'market', state: 'New York' },
{ id: 4, name: 'philps', city: 'booket', state: 'Texas' },
{ id: 5, name: 'smith', city: 'brookfield', state: 'Florida' },
{ id: 6, name: 'Broom', city: 'old street', state: 'Florida' },
];
const result = data.reduce((p, c) => {
const found = p.findIndex(p => p.state === c.state);
if (found !== -1) {
delete c.state;
p[found].people.push(c);
} else {
p.push({
id: p.length + 1,
state: c.state,
people: [{
id: c.id,
name: c.name,
city: c.city
}]
})
}
return p
}, []);
console.log(result);

最新更新