-6

How to group by based on two json key which is f and b My json array

var json=[
    {   s:'s',  f:1,  b:1,  q:2   },
    {   s:'s',  f:1,  b:1,  q:3   },
    {   s:'s',  f:2,  b:1,  q:2   },
    {   s:'s',  f:2,  b:1,  q:2   },
    {   s:'s',  f:1,  b:2,  q:2   },
    {   s:'s',  f:1,  b:2,  q:2   },
    {   s:'s',  f:0,  b:1,  q:2   },
    {   s:'s',  f:0,  b:1,  q:2   },
    {   s:'s',  f:1,  b:0,  q:2    },
    {   s:'s',  f:1,  b:0, q:2    },
    {   s:'s',  f:0,  b:0,  q:2    },
    {   s:'s',  f:0,  b:0, q:2    },

];

Expected Output

 var op=[
    {   s:'s',  f:1,  b:1,  q:5   },
    {   s:'s',  f:2,  b:1,  q:4   },
    {   s:'s',  f:1,  b:2,  q:4   },
    {   s:'s',  f:0,  b:1,  q:4   },
    {   s:'s',  f:1,  b:0,  q:4   },
    {   s:'s',  f:0,  b:0,  q:4   },

];

2

1 Answer 1

0

var json=[
    {   s:'s',  f:1,  b:1,  q:2   },
    {   s:'s',  f:1,  b:1,  q:3   },
    {   s:'s',  f:2,  b:1,  q:2   },
    {   s:'s',  f:2,  b:1,  q:2   },
    {   s:'s',  f:1,  b:2,  q:2   },
    {   s:'s',  f:1,  b:2,  q:2   },
    {   s:'s',  f:0,  b:1,  q:2   },
    {   s:'s',  f:0,  b:1,  q:2   },
    {   s:'s',  f:1,  b:0,  q:2   },
    {   s:'s',  f:1,  b:0,  q:2   },
    {   s:'s',  f:0,  b:0,  q:2   },
    {   s:'s',  f:0,  b:0,  q:2   },
];

var result = Object.values(json.reduce((list, cur) => {
    if(list[cur.f + ',' + cur.b])
        list[cur.f + ',' + cur.b].q += cur.q
    else
        list[cur.f + ',' + cur.b] = Object.assign({}, cur)
    return list
}, {}))
console.log(result)

Sign up to request clarification or add additional context in comments.

2 Comments

Thank You very much
glad to help you. accepting as the answer would be great.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.