Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
225 views
in Technique[技术] by (71.8m points)

javascript - 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. 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

 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'

Is anything missing here !

Any help on this appreciated !

question from:https://stackoverflow.com/questions/66051282/concatenate-array-in-vue-js

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

You can group your array item based on userid and push placename into array and sum up price for same userid.

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

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...