Home > Blockchain >  How could I sum a property of each object for separate object arrays?
How could I sum a property of each object for separate object arrays?

Time:06-20

I had an object which in it had objects which each had an array of objects with 0..n objects. The main object looked something like this:

{
    obj1: [{obj1.1}, {obj1.2}, {obj1.3}],
    obj2: [{obj2.1}]
    obj3: [{obj3.1}, {obj3.2}]
}

Each object (obj1, obj2 and obj3) held a group of common objects in an array of objects. E.g. obj1 has a group of objects in an object array (obj1.1, obj1.2 and obj1.3) all which have a common property that groups them together.

I want to now be able to iterate over each object separately in each object array in order to sum a particular property (which each object has) for each object array.

I have used Object.keys to iterate over each object array, although I still am unable to get a separate summed value per object array.

For example:

{
    obj1: [
       0: { price: 10 }
       1: { price: 10 }
       2: { price: 10 }
    ],
    obj2: [
       0: { price: 10 }
    ],
    obj3: [
       0: { price: 10 }
       1: { price: 10 }
    ]
}

I want to be able to sum the property price for each individual object array. Therefore for obj1 I should have a summed amount of 30. For obj2 I should have a summed amount of 10, and lastly for obj3 I should have a summed amount of 20.

I can iterate over each object array using Object.keys, however as it stands now, when iterating over each individual element in each object array (using a foreach), I am only summing a final amount for all objects in all three object arrays. I.e. I am getting a summed amount of 60.

var total = 0;
for (var key of Object.keys(result)) {
    result[key].forEach(element => {
        total  = element.Price;
    });
};
console.log(total);

What could I use to get the three individually summed amounts per object array?

CodePudding user response:

function sum(prices)
{
  let total = 0;
  prices.forEach((entry) => total  = entry.price);
  return total;
}

console.log(sum(obj1));
console.log(sum(obj2));
console.log(sum(obj3));

Why was this hard again? You had the right code, just needed to break things out.

CodePudding user response:

  • Using Object#entries, get the key-array pairs
  • Using Array#reduce, iterate over this list
  • In every iteration, using Array#reduce, you can calculate the total price and save it as a value for the current key

const data = {
  obj1: [ { price: 10 }, { price: 10 }, { price: 10 } ],
  obj2: [ { price: 10 } ],
  obj3: [ { price: 10 }, { price: 10 } ]
};

const res = Object.entries(data).reduce((totalMap, [key, arr]) => ({
  ...totalMap,
  [key]: arr.reduce((total, { price }) => total   price, 0)
}), {});

console.log(res);

CodePudding user response:

yet here another way to get the result as an array:

let obj={obj1:[{price:10},{price:10},{price:10}],obj2:[{price:10}],obj3:[{price:10},{price:10}]};


let result = Object.entries(obj)
    .map(([k,v]) =>  ( {[k]:v.reduce((acc,e) => acc =e.price ,0)} ) )

console.log(result)

CodePudding user response:

You could sepearte the tasks, one for getting a total value of a certain key and another one for iterating the keys of the object.

const
    getTotal = (array, key) => array.reduce((t, o) => t   o[key], 0),
    data = { obj1: [{ price: 10 }, { price: 10 }, { price: 10 }], obj2: [{ price: 10 }], obj3: [{ price: 10 }, { price: 10 }] },
    result = {};

for (const key in data) result[key] = getTotal(data[key], 'price');

console.log(result);

CodePudding user response:

You can map over Object.entries, using Array#reduce to get the sum of each array, and then use Object.fromEntries to get an object result.

const obj={obj1:[{price:10},{price:10},{price:10}],obj2:[{price:10}],obj3:[{price:10},{price:10}]};
let res = Object.fromEntries(Object.entries(obj).map(([k, v])=>
            [k, v.reduce((a,b)=>a b.price,0)]));
console.log(res);

  • Related