“Jumlah dua objek JavaScript” Kode Jawaban

jumlah array objek 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

Jumlah dua objek 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

Jumlah array objek dalam 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'));

Jawaban yang mirip dengan “Jumlah dua objek JavaScript”

Pertanyaan yang mirip dengan “Jumlah dua objek JavaScript”

Lebih banyak jawaban terkait untuk “Jumlah dua objek JavaScript” di JavaScript

Jelajahi jawaban kode populer menurut bahasa

Jelajahi bahasa kode lainnya