[英]How to get new array from old array in 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);
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.