简体   繁体   English

在 vue.js 中连接数组

[英]Concatenate array in vue.js

I have following array with me where records are shown per user我有以下数组,每个用户显示记录

let data = [
  { userid: 1, placename: abc,  price: 10 },
  { userid: 1, placename: pqr,  price: 20 },  
  { userid: 1, placename: xyz , price: 30},
  { userid: 2, placename: abc , price: 40},
  { userid: 2, placename: lmn , price: 50}

So, I want to transpose this data group by userid, by concatenation of place name and sum of price.所以,我想通过用户ID、地名和价格总和的连接来转置这个数据组。 It should be look like below它应该如下所示

UseId   PlaceName   Price
1       abc,xyz,pqr 60
2       abc,lmn     90

And I am binding this data to bootstrap vue b-table component As of now I have done like this我正在将这些数据绑定到引导 vue b-table 组件到目前为止,我已经这样做了

 groupby: function(array, key) {
            const result = {};
            array.forEach(item => {
                if (!result[item[key]]) {
                    result[item[key]] = [];
                }
                result[item[key]].push(item);
            });
           
            return result;
        },

And calling this while view is getting initialized,并在视图初始化时调用它,

groupby(this.list,'userid');

though I am getting all records in row as per user, but I am not able to concatenate the values and doing total.尽管我按用户逐行获取所有记录,但我无法连接这些值并进行总计。

While binding to table it is giving error 'Expected Arrat,got object'绑定到表时出现错误“预期的 Arrat,得到对象”

Is anything missing here !这里有什么遗漏吗!

Any help on this appreciated !对此的任何帮助表示赞赏!

Try out to filter the items that have the same userid then join place names and sum their prices:尝试过滤具有相同用户 ID 的项目,然后加入地名并求和它们的价格:

 array.forEach(item => {
                if (!result[item[key]]) {
                    result[item[key]] = [];
                }
        let matched=array.filter(el=>el.UseId===item.UseId);
         result[item[key]].push(
           {
              UseId:item.UseId,
              placeName:matched.map(e=>e.placename).join(),
              Price:matched.reduce((a, b) => a + b.price, 0)

           });//push end

 });

You can group your array item based on userid and push placename into array and sum up price for same userid .您可以根据userid对数组项进行分组,并将placename推入数组并总结相同useridprice

 const data = [ { userid: 1, placename: 'abc', price: 10 }, { userid: 1, placename: 'pqr', price: 20 }, { userid: 1, placename: 'xyz', price: 30}, { userid: 2, placename: 'abc', price: 40}, { userid: 2, placename: 'lmn', price: 50}], result = Object.values(data.reduce((r,o) => { r[o.userid] = r[o.userid] || {userid: o.userid, placename: [], price: 0}; r[o.userid].placename.push(o.placename); r[o.userid].price += o.price; return r; },{})); console.log(result);
 .as-console-wrapper { max-height: 100%;important: top; 0; }

Whenever you feel like making an empty object and using array.map to populate it, try using.reduce instead每当您想制作一个空的 object 并使用 array.map 填充它时,请尝试使用.reduce

 const data = [ { userid: 1, placename: "abc", price: 10 }, { userid: 1, placename: "pqr", price: 20 }, { userid: 1, placename: "xyz", price: 30}, { userid: 2, placename: "abc", price: 40}, { userid: 2, placename: "lmn", price: 50} ]; const groupBy = (arr, key) => Object.values( arr.reduce((acc, item) => { const k = item[key]; if (.acc[k]) { acc[k] = {..;item}. } else { acc[k],placename += "." + item;placename. acc[k].price += item;price; } return acc, }; {}) ). console,log(groupBy(data; "userid"));

I split the solution in 3 steps, X, Y and Z:我将解决方案分为 3 个步骤,X、Y 和 Z:

X = group the rows by userid; X = 按用户 ID 对行进行分组;

Y = concat the placenames and sum the prices; Y = 连接地名并求和价格;

Z = make a simpler object. Z = 制作一个更简单的 object。

let data = [
    { userid: 1, placename: 'abc', price: 10 },
    { userid: 1, placename: 'pqr', price: 20 },
    { userid: 1, placename: 'xyz', price: 30 },
    { userid: 2, placename: 'abc', price: 40 },
];

const X = data.reduce((a, { userid, placename, price }) => { a[userid] = [...(a[userid] || []), { placename, price }]; return a }, {})
const Y = Object.entries(X).map(([userid, items]) => { return [userid, items.reduce((a, c) => { a.placename = [...a.placename.split(',').filter(s => !!s), c.placename].join(','); a.price += c.price; return a; }, { placename: '', price: 0 })]; });
const Z = Y.map(([userid, { placename, price }]) => ({ userid, placename, price }))

console.log(Z)

You can use a single line solution too:您也可以使用单行解决方案:

let data = [
    { userid: 1, placename: 'abc', price: 10 },
    { userid: 1, placename: 'pqr', price: 20 },
    { userid: 1, placename: 'xyz', price: 30 },
    { userid: 2, placename: 'abc', price: 40 },
]
const doIt = (data) => Object.entries(data.reduce((a, { userid, placename, price }) => { a[userid] = [...(a[userid] || []), { placename, price }]; return a }, {})).map(([userid, items]) => { return [userid, items.reduce((a, c) => { a.placename = [...a.placename.split(',').filter(s => !!s), c.placename].join(','); a.price += c.price; return a; }, { placename: '', price: 0 })]; }).map(([userid, { placename, price }]) => ({ userid, placename, price }))
console.log(doIt(data))

Have fun!玩得开心!

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM