Javascript合并多维数组?

问题描述 投票:0回答:2

我想合并相同类型的数组。它来自数据库如下。

const array =[
{
  name: 'Iphone',
  date: '01.01.2024',
  img: 'img/iphone.png',
  cost: 2500,
  username:"Joe",
},
{
  name: 'Samsung',
  date: '01.01.2024',
  img: 'img/samsung.png',
  cost: 2000,
  username:"Adam",
},
{
  name: 'Samsung',
  date: '01.01.2024',
  img: 'img/samsung.png',
  cost: 2000,
  username:"Alvin",
}
]

我需要将其转换为以下数组?

const array =[
{
  name: 'Iphone',
  date: '01.01.2024',
  img: 'img/iphone.png',
  cost: 2500,
  username:"Joe",
},
{
  name: 'Samsung',
  date: '01.01.2024',
  img: 'img/samsung.png',
  cost: 2000,
  usernames:[{
    username:"Adam"
  },
  {
    username:"Alvin"
  }]
  ,
},
]

你能帮我吗?

javascript arrays mergesort
2个回答
0
投票
const data = [
    {
        name: 'Iphone',
        date: '01.01.2024',
        img: 'img/iphone.png',
        cost: 2500,
        username: 'Joe',
    },
    {
        name: 'Samsung',
        date: '01.01.2024',
        img: 'img/samsung.png',
        cost: 2000,
        username: 'Adam',
    },
    {
        name: 'Samsung',
        date: '01.01.2024',
        img: 'img/samsung.png',
        cost: 2000,
        username: 'Alvin',
    },
];

const processedData = data.reduce((acc, curr) => {
    const found = acc.find(
        (user) =>
            user.name === curr.name &&
            user.date === curr.date &&
            user.img === curr.img &&
            user.cost === curr.cost
    );

    if (found) {
        found.usernames.push({ username: curr.username });
    } else {
        acc.push({
            name: curr.name,
            date: curr.date,
            img: curr.img,
            cost: curr.cost,
            usernames: [{ username: curr.username }],
        });
    }

    return acc;
}, []);

此代码使用reduce函数迭代初始数组,并通过检查是否已经存在具有相同“name”、“date”、“img”和“cost”的对象来创建所需格式的新数组(resultArray)存在于累加器(acc)中。如果存在,它将“用户名”推送到“用户名”数组。否则,它会创建一个新对象并使用当前的“用户名”初始化“用户名”数组。


0
投票

let names = [...new Set(array.map(i=>i.name))]

let array2 = names.map(name => ({
  ...array.find(i => i.name===name),
  usernames: array.filter(i => i.name===name).map(({username}) => ({username})),
}))

array2.forEach(i => delete i.username)

console.log(array2)
First, get the unique phone names.

Then, for each name, find the matching phone entry, and extract all properties in to a new object. Then, add in all usernames for that phone name.

Finally, delete the username property for each object in the resulting array, so that there is only a usernames property at the top level.

© www.soinside.com 2019 - 2024. All rights reserved.