如何在react native中从旧阵列获取新阵列?

efzxgjgh  于 2022-11-30  发布在  React
关注(0)|答案(1)|浏览(124)

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',
        }
      ]
    }
  ];
lx0bsm1f

lx0bsm1f1#

这个就行了。

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);

相关问题