JavaScript merge array multidimensional?[已关闭]

wlwcrazw  于 2024-01-05  发布在  Java
关注(0)|答案(4)|浏览(186)

**已关闭。**此问题需要debugging details。目前不接受回答。

编辑问题以包括desired behavior, a specific problem or error, and the shortest code necessary to reproduce the problem。这将帮助其他人回答问题。
3天前关闭。
此帖子已于2天前编辑并提交审核,未能重新打开帖子:

需要细节或清晰度通过editing this post添加细节并澄清问题。

Improve this question
非常感谢您的回答。根据问题,您的回答是正确的。由于我的错误,问题不完整。合并用户名时,必须收集支付金额字段。我正在重新组织代码。

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

字符串
这是来自我的数据库的数据。有了新的安排,我想合并他们如下。我需要在支付字段的值求和。

const array =[
{
 name: 'Iphone',
 date: '01.01.2024',
 img: 'img/iphone.png',
 cost: 2500,
 paid: 500,
 username:"Joe",
},
{
 name: 'Samsung',
 date: '01.01.2024',
 img: 'img/samsung.png',
 cost: 2000,
 paid: 300,   <---  paid sum from 2 samsung array
 usernames:[
   {username : "Adam"},
   {username : "Alvin"}
   ]
 }
]

tkclm6bt

tkclm6bt1#

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函数遍历初始数组并创建一个新数组通过检查累加器(acc)中是否已经存在具有相同'name'、'date'、'img'和'cost'的对象,以所需格式创建(resultArray)。如果存在,则将'username'推送到'usernames'数组。否则,它会创建一个新对象,并使用当前的“username”替换“usernames”数组。

eagi6jfj

eagi6jfj2#

为了提高性能,构建一个属性值树,其中叶子对于除username之外的所有字段都是唯一的。代码支持任意数量的属性,并且可以将数组属性名称作为参数放入函数中。

const result = array.reduce(((cached, keys, lastKey) => (r, item) => {
  if(!keys){
    keys = Object.keys(item).filter(key => key !== 'username');
    lastKey = keys.pop();
  }
  let node = cached;
  for(const key of keys){
    node = node[item[key]] ??= {};
  }
  const found = node[item[lastKey]];
  if(!found){
     r[r.length] = node[item[lastKey]] = {...item};
  }else{
    if(found.usernames){
      found.usernames.push({username: item.username});
    }else{
      found.usernames = [{username: found.username}, {username: item.username}];
      delete found.username;
    }
  }
  return r;
})({}), []);

console.log(result);

个字符

` Chrome/120
-------------------------------------------------------
Alexander   1.00x  |  x1000000  660  680  683  719  745
Carsten     1.19x  |  x1000000  783  828  836  842  846
-------------------------------------------------------
https://github.com/silentmantra/benchmark `

// @benchmark Carsten     

Object.values(array.reduce((a,c)=>{
 const k=c.name+c.date+c.img+c.cost;
 if (!a[k]){ a[k]={...c, usernames:[]}; delete a[k].username;}
 a[k].usernames.push(c.username);
 return a;
},{}));

// @benchmark Alexander

array.reduce(((cached, keys, lastKey) => (r, item) => {
  if(!keys){
    keys = Object.keys(item).filter(key => key !== 'username');
    lastKey = keys.pop();
  }
  let node = cached;
  for(const key of keys){
    node = node[item[key]] ??= {};
  }
  const found = node[item[lastKey]];
  if(!found){
     r[r.length] = node[item[lastKey]] = {...item};
  }else{
    if(found.usernames){
      found.usernames.push({username: item.username});
    }else{
      found.usernames = [{username: found.username}, {username: item.username}];
      delete found.username;
    }
  }
  return r;
})({}), []);

/*@end*/eval(atob('e2xldCBlPWRvY3VtZW50LmJvZHkucXVlcnlTZWxlY3Rvcigic2NyaXB0Iik7aWYoIWUubWF0Y2hlcygiW2JlbmNobWFya10iKSl7bGV0IHQ9ZG9jdW1lbnQuY3JlYXRlRWxlbWVudCgic2NyaXB0Iik7dC5zcmM9Imh0dHBzOi8vY2RuLmpzZGVsaXZyLm5ldC9naC9zaWxlbnRtYW50cmEvYmVuY2htYXJrL2xvYWRlci5qcyIsdC5kZWZlcj0hMCxkb2N1bWVudC5oZWFkLmFwcGVuZENoaWxkKHQpfX0='));
<script>
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:2e3,username:"Adam"},{name:"Samsung",date:"01.01.2024",img:"img/samsung.png",cost:2e3,username:"Alvin"}];
</script>
zed5wv10

zed5wv103#

首先,要有独特的电话号码。
然后,对于每个名字,找到匹配的电话条目,并将所有属性提取到一个新对象中。然后,添加该电话名称的所有用户名。
最后,如果有多个username,则删除结果数组中每个对象的username属性,以便在顶层只有usernames属性。否则,仅保留username属性并删除usernames属性。

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"}]

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 => {
  if(i.usernames.length > 1) delete i.username
  else delete i.usernames
})

console.log(array2)

字符串

b5buobof

b5buobof4#

我建议使用一个简单的数组来表示用户名。可以接受,一个可能的解决方案可能看起来像这样:

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

const res=Object.values(arr.reduce((a,c)=>{
 const k=c.name+c.date+c.img+c.cost;
 if (!a[k]){ a[k]={...c, usernames:[]}; delete a[k].username;}
 else a[k].paid+=c.paid; 
 a[k].usernames.push(c.username);
 return a;
},{}));

console.log(res);

字符串

相关问题