解构对象字段并在 Javascript 中计算总和



我在弄清楚如何解构和添加带有字段的对象的总和时遇到了麻烦。以前,我们在对象数组中错误地分离对象。现在它们被加在 1 个对象中,它看起来像这样:

{
  "3" {
   petIds:{
    "113": {"estimatedEats": 10, "owners": {"female":{"kids":1, "adult":2, "senior":10}}, "male":{"kids":1, "adult":2, "senior":10}}
     "9": {"estimatedEats": 1, owners: {…}}}
  "6":{
   petIds:{
     "113": {"estimatedEats": 5, "owners": {…}}
     "9": {"estimatedEats": 6, "owners": {…}}
     "1": {"estimatedEats": 7, "owners": {…}}}
  }

以前我可以映射对象数组。我想得到一个看起来像这样的对象数组:

[{petIds:113, "estimatedEats":15, "owners": (sum of owner description)}...]

有没有办法将每个字段转换为对象数组?我认为这样做并映射数组会更容易。

这应该让你开始:

var x = {
  3:{
   petIds:{
    113: {estimatedEats: 10, owners: {}},
     9: {estimatedEats: 1, owners: {}}
   }
  },
  6:{
   petIds:{
     113: {"estimatedEats": 5, "owners": {}},
     9: {"estimatedEats": 6, "owners": {}},
     1: {"estimatedEats": 7, "owners": {}}
   }
  }
};
var pets = [];
Object.keys(x).forEach(function(key) {
    var y = x[key];
    Object.keys(y).forEach(function(objKey) {
        if(objKey === 'petIds'){
          var z = y[objKey];
          Object.keys(z).forEach(function(petKey) {
            var pet = Object.assign({},z[petKey]);
            pet.id = parseInt(petKey);
            pets.push(pet);
          });
        };
    });
});
var sumPets = [];
pets.forEach(function(p){
  var idx = sumPets.findIndex(function(i){
    return i.id === p.id;
  });
  if(idx < 0){
    sumPets.push(p);
  } else {
    sumPets[idx].estimatedEats = sumPets[idx].estimatedEats + p.estimatedEats;
  }
});
console.log(sumPets);

我不太确定我是否理解您要实现的目标,但我会尽力回答:)

有没有办法将每个字段转换为对象数组?我认为这样做并映射数组会更容易。

Object.values创建一个包含对象所有值的数组。这就是你要找的吗?

这是一个代码笔,我在其中使用 ObjectArray 方法对estimatedEats求和。我认为您也应该能够基于此总结其他属性。

const data = {
  3: {
    petIds: {
      113: {
        estimatedEats: 10,
        owners: { female: { kids: 1, adult: 2, senior: 10 } },
        male: { kids: 1, adult: 2, senior: 10 }
      },
      1: {
        estimatedEats: 120,
        owners: { female: { kids: 1, adult: 2, senior: 10 } },
        male: { kids: 1, adult: 2, senior: 10 }
      }
    }
  },
  6: {
    petIds: {
      113: {
        estimatedEats: 5,
        owners: { female: { kids: 1, adult: 2, senior: 10 } },
        male: { kids: 1, adult: 2, senior: 10 }
      },
      1: {
        estimatedEats: 5,
        owners: { female: { kids: 1, adult: 2, senior: 10 } },
        male: { kids: 1, adult: 2, senior: 10 }
      }
    }
  }
};
const groupedById = Object.values(data).reduce((acc, { petIds }) => {
  Object.entries(petIds).forEach(([key, value]) => {
    acc[key] = acc[key] || [];
    acc[key].push(value);
  });
  return acc;
}, {});
const summedUp = Object.entries(groupedById).map(
  ([key, value]) =>
    value.reduce(
      (acc, row) => {
        acc.estimatedEats += row.estimatedEats;
        return acc;
      },
      { estimatedEats: 0, petIds: key }
    ),
  []
);
console.log("Result:", summedUp);

更新:也将代码粘贴到我的答案中。

相关内容

  • 没有找到相关文章