【问题标题】:JavaScript: Add up numbers in nested array of objectsJavaScript:将嵌套对象数组中的数字相加
【发布时间】:2020-07-22 15:41:28
【问题描述】:

我正在尝试获取平均价格,将价格相乘并将嵌套对象数组的数量相加,但我不知道如何获得正确的结果,有人可以帮忙。提前致谢

数组类型:

[
CreatAsset_kcnuvkr7: (3) [{…}, {…}, {…}]
CreatAsset_kcop95ya: (2) [{…}, {…}]
CreatAsset_kcoprqc4: (3) [{…}, {…}, {…}]
CreatAsset_kcqjmhyh: (5) [{…}, {…}, {…}, {…}, {…}]
]

对象数据:

[
  {
    latestPrice: { stringValue: 207.88 },
    purchaseDate: { stringValue: "1594829893159" },
    purchaseQty: { stringValue: "50" },
    waterMark: { stringValue: "CreatAsset_kcnuvkr7" }
  },
  {
    latestPrice: { stringValue: 9.88 },
    purchaseDate: { stringValue: "1593868712336" },
    purchaseQty: { stringValue: "30.00" },
    waterMark: { stringValue: "CreatAsset_kcnuvkr7" }
  },
  {
    latestPrice: { stringValue: 98.8 },
    purchaseDate: { stringValue: "1594829859268" },
    purchaseQty: { stringValue: "100" },
    waterMark: { stringValue: "CreatAsset_kcnuvkr7" }
  }
];

我想要的结果:

(totalPrice = latestPrice * purchaseQty ), (avgPrice = (latestPrice index[0] + latestPrice index[1] + latestPrice index[2] / 3)

{
  avgPrice: {
    stringValue: 105.52
  }
  totalPurchaseQty: {
    stringValue: "180"
  }
  totalPrice1: {
    stringValue: "10394.00"
  }
  totalPrice2: {
    stringValue: "296.40"
  }
  totalPrice3: {
    stringValue: "9880.00"
  }
  waterMark: {
    stringValue: "CreatAsset_kcnuvkr7"
  }
}

我的代码:

(result is the Array type of above)

let latestPrice = [];
for (let i in result) {
  if (result.hasOwnProperty(i)) {
    result[i].map((res) => {
      latestPrice.push({
        latestPrice: res.latestPrice.stringValue,
        waterMark: res.waterMark.stringValue,
      });
    });
  }
}

【问题讨论】:

  • 请将您的代码重新格式化为有效的 JSON 或 JavaScript。
  • 您说您希望 avgPrice 是每个 latestPrice 的总和除以每个 purchaseQty 的总和,但在您的示例中,您实际上将其计算为每个 latestPrice 的总和除以数组的长度。
  • @GirkovArpa 是的,你是对的,对不起,我要编辑

标签: javascript arrays ecmascript-6 javascript-objects


【解决方案1】:
Object.entries(data).forEach(([watermark, array]) => {
  data[watermark] = array.reduce((result, object, i) => {
    const { latestPrice, purchaseQty } = Object.fromEntries(Object.entries(object)
      .map(([key, { stringValue }]) => ([key, +stringValue])));
    result['totalPrice' + (i + 1)] = latestPrice * purchaseQty;
    result.avgPrice += latestPrice;
    result.totalPurchaseQty += purchaseQty;
    i == array.length - 1 && (result.avgPrice /= array.length);
    return result;
  }, { avgPrice: 0, totalPurchaseQty: 0, watermark });
});

活生生的例子:

const data = {
  CreatAsset_kcnuvkr7: [
    {
      latestPrice: { stringValue: 207.88 },
      purchaseDate: { stringValue: '1594829893159' },
      purchaseQty: { stringValue: '50' },
      waterMark: { stringValue: 'CreatAsset_kcnuvkr7' }
    }, {
      latestPrice: { stringValue: 9.88 },
      purchaseDate: { stringValue: "1593868712336" },
      purchaseQty: { stringValue: "30.00" },
      waterMark: { stringValue: "CreatAsset_kcnuvkr7" }
    }, {
      latestPrice: { stringValue: 98.80 },
      purchaseDate: { stringValue: "1594829859268" },
      purchaseQty: { stringValue: "100" },
      waterMark: { stringValue: "CreatAsset_kcnuvkr7" }
    }
  ]
}

Object.entries(data).forEach(([watermark, array]) => {
  data[watermark] = array.reduce((result, object, i) => {
    const { latestPrice, purchaseQty } = Object.fromEntries(Object.entries(object)
      .map(([key, { stringValue }]) => ([key, +stringValue])));
    result['totalPrice' + (i + 1)] = latestPrice * purchaseQty;
    result.avgPrice += latestPrice;
    result.totalPurchaseQty += purchaseQty;
    i == array.length - 1 && (result.avgPrice /= array.length);
    return result;
  }, { avgPrice: 0, totalPurchaseQty: 0, watermark });
});

console.log(data);

【讨论】:

    【解决方案2】:

    也许你追求的是这样的:

    const data = [
      {
        latestPrice: { stringValue: 207.88 },
        purchaseDate: { stringValue: "1594829893159" },
        purchaseQty: { stringValue: "50" },
        waterMark: { stringValue: "CreatAsset_kcnuvkr7" }
      },
      {
        latestPrice: { stringValue: 9.88 },
        purchaseDate: { stringValue: "1593868712336" },
        purchaseQty: { stringValue: "30.00" },
        waterMark: { stringValue: "CreatAsset_kcnuvkr7" }
      },
      {
        latestPrice: { stringValue: 98.8 },
        purchaseDate: { stringValue: "1594829859268" },
        purchaseQty: { stringValue: "100" },
        waterMark: { stringValue: "CreatAsset_kcnuvkr7" }
      }
    ];
    
    const average = arr => arr.reduce((p, c) => p + c, 0) / arr.length;
    console.log("Average Price", average(data.map(d => d.latestPrice.stringValue)));
    
    const total = data.map(d =>
      (d.latestPrice.stringValue * d.purchaseQty.stringValue).toFixed(2)
    );
    console.log("Total prices:", total);
    
    const totalPurchaseQty = data
      .map(d => d.purchaseQty.stringValue)
      .reduce((a, b) => Number(a) + Number(b), 0);
    console.log("Total Purchse quantity:", totalPurchaseQty);

    这很有趣,令人愉快的函数式编程。您可以使用.map() 将您的对象转换为您想要使用的值并从那里应用您的公式。 :)

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2022-12-18
      • 2018-01-24
      • 2020-06-21
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多