-1

I have this data,

json:

var data = [{a:1,b:{amount: 10}, c:1},
            {a:2,b:{amount: 20}, c:1}, 
            {a:1,b:{amount: 30}, c:2}
           ];

and I want to do something like this:

SELECT SUM(b.amount) FROM data GROUP BY a, c
2
  • Javascript objects are not databases. Have you tried writing any code yet to implement the functionality you want? Commented Dec 5, 2018 at 1:31
  • i've tried using alaSQL.js but i just can't get the b.amount... Commented Dec 5, 2018 at 1:32

2 Answers 2

2

You're trying to sum properties in an array of objects.

This will do it for you:

let sum = [];
data.forEach(function(el){
    if(sum[el.a] == undefined) sum[el.a] = []; 
    if(sum[el.a][el.c] == undefined) sum[el.a][el.c] = 0; 
    sum[el.a][el.c] += el.b.amount
});

You can then access the sum for a = 1, c = 2 with sum[1][2].

This code will work with larger data sets which require adding.

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

1 Comment

Just multiply the amount by the quantity. Like this: sum[el.a][el.c] += el.b.amount * el.b.qty;
0

If I understand your questions correctly, you are asking how you can perform grouping and aggregation on a JSON object. As SQL can only be used in the realm of a database, you will need to use javascript functions such as forEach(), map(), filter(), reduce(), etc.

To make it easy on yourself, I recommend using a library like Lodash or Underscore.

Here is an example using Lodash:

let data = [
  {a:1, b:{amount: 10}, c:1},
  {a:2, b:{amount: 20}, c:1},
  {a:1, b:{amount: 30}, c:2}
];

let results = _.sumBy(data, 'b.amount');

console.log(results);
<script src="https://cdn.jsdelivr.net/npm/[email protected]/lodash.min.js"></script>

Using these libraries can take away a lot of the complexity of writing your own scripting, especially when dealing with nested objects and arrays.

I recommend using pure JS whenever possible and resort to libraries only when necessary.

1 Comment

ooh lodash, ya i've heard of it. i'll consider this also.. thank you

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.