“Summe zwei Objekte JavaScript” Code-Antworten

Summe von Objekten JavaScript

var accounts = [
  { name: 'James Brown', msgCount: 123 },
  { name: 'Stevie Wonder', msgCount: 22 },
  { name: 'Sly Stone', msgCount: 16 },
  { name: 'Otis Redding', msgCount: 300 }  // Otis has the most messages
];

// get sum of msgCount prop across all objects in array
var msgTotal = accounts.reduce(function(prev, cur) {
  return prev + cur.msgCount;
}, 0);

console.log('Total Messages:', msgTotal); // Total Messages: 461
Philan ISithembiso

Summe zwei Objekte JavaScript

var obj1 = {
  a: 12,
  b: 8,
  c: 17
};

var obj2 = {
  a: 12,
  b: 8,
  c: 17
};

var obj3 = {
  a: 12,
  b: 8,
  c: 17
};


function sumObjectsByKey(...objs) {
  return objs.reduce((a, b) => {
    for (let k in b) {
      if (b.hasOwnProperty(k))
        a[k] = (a[k] || 0) + b[k];
    }
    return a;
  }, {});
}

console.log(sumObjectsByKey(obj1, obj2, obj3));
 Run code snippet
TalaatMagdy

Summe von Objekten in JavaScript

class fruitCollection extends Array {
    sum(key) {
        return this.reduce((a, b) => a + (b[key] || 0), 0);
    }
}
const fruit = new fruitCollection(...[
    {  description: 'orange', Amount: 50},
    {  description: 'orange', Amount: 50},
    {  description: 'apple', Amount: 75},
    {  description: 'kiwi', Amount: 35},
    {  description: 'watermelon', Amount: 25 },]);

console.log(fruit.sum('Amount'));

Ähnliche Antworten wie “Summe zwei Objekte JavaScript”

Fragen ähnlich wie “Summe zwei Objekte JavaScript”

Weitere verwandte Antworten zu “Summe zwei Objekte JavaScript” auf JavaScript

Durchsuchen Sie beliebte Code-Antworten nach Sprache

Durchsuchen Sie andere Codesprachen