【问题标题】:Adding array of json object value based on parameter in Typescript基于Typescript中的参数添加json对象值数组
【发布时间】:2018-12-01 14:11:10
【问题描述】:

我有一个平面 JSON 数组,其中重复了 identifiercategoryIdcategory

    data: [
    {
        "identifier": "data",
        "categoryId": "1",
        "category": "Baked goods",
        "product": "Aunt Hattie's",
        "price": "375"
    },
    {
        "identifier": "data",
        "categoryId": "1",
        "category": "Baked goods",
        "product": "Back to Nature",
        "price": "343"
    },        
    {
        "identifier": "data",
        "categoryId": "2",
        "category": "Cakes",
        "product": "Mars Muffin (McVitie's)",
        "price": "465"
    },
    {
        "identifier": "data",
        "categoryId": "2",
        "category": "Cakes",
        "product": "McVitie's",
        "price": "251"
    },
    {
        "identifier": "data",
        "categoryId": "2",
        "category": "Cakes",
        "product": "Mr Kipling",
        "price": "260"
    },
    {
        "identifier": "data",
        "categoryId": "2",
        "category": "Cakes",
        "product": "Mr Kipling Frosty Fancies",
        "price": "210"
    },
    {
        "identifier": "data",
        "categoryId": "3",
        "category": "Dairy products",
        "product": "Amul",
        "price": "474"
    },
    {
        "identifier": "data",
        "categoryId": "3",
        "category": "Dairy products",
        "product": "Borden",
        "price": "184"
    },
    {
        "identifier": "data",
        "categoryId": "3",
        "category": "Dairy products",
        "product": "Broughton Foods Company",
        "price": "43"
    },
]

如何合计每个类别的价格并将对象推入每个类别的末尾,identifieras Total 与总值。我知道将对象推入 JSON 数组最后将对象推入。但这很好,因为我可以像这样使用sort 函数对数组进行排序:

function compare(a,b) {
  if (a.categoryId < b.categoryId)
  return -1;
  if (a.categoryId> b.categoryId)
  return 1;
 return 0;
}

data.sort(compare);

已编辑

我希望输出是这样的:

: [
    {
        "identifier": "data",
        "categoryId": "1",
        "category": "Baked goods",
        "product": "Aunt Hattie's",
        "price": "110"
    },
    {
        "identifier": "data",
        "categoryId": "1",
        "category": "Baked goods",
        "product": "Back to Nature",
        "price": "344"
    },
    {
        "identifier": "Total",
        "categoryId": "1",
        "category": "Baked goods",
        "price": "454"
    },
    {
        "identifier": "data",
        "categoryId": "2",
        "category": "Cakes",
        "product": "Mars Muffin (McVitie's)",
        "price": "455"
    },
    {
        "identifier": "data",
        "categoryId": "2",
        "category": "Cakes",
        "product": "Secret Recipe",
        "price": "471"
    },
    {
        "identifier": "data",
        "categoryId": "2",
        "category": "Cakes",
        "product": "Vimto Jam Tarts",
        "price": "235"
    },
    {
        "identifier": "Total",
        "categoryId": "2",
        "category": "Cakes",
        "price": "1161"
    },
    {
        "identifier": "data",
        "categoryId": "3",
        "category": "Dairy products",
        "product": "Alta Dena",
        "price": "158"
    },
    {
        "identifier": "data",
        "categoryId": "3",
        "category": "Dairy products",
        "product": "Chivers",
        "price": "399"
    },
    {
        "identifier": "Total",
        "categoryId": "3",
        "category": "Dairy products",
        "price": "557"
    }
]

【问题讨论】:

  • 你能添加预期的输出吗?
  • @Rahul 我已经更新了预期的输出

标签: javascript arrays json typescript


【解决方案1】:

您可以使用哈希表来引用相同的类别,并为每个总组添加另一个对象。

data 的末尾,现在包括所有总数。

要将数据排序到每个类别的顶部和底部的总计,您可以添加总计检查并将此部分移动到类别部分的末尾。

var data = [{ identifier: "data", categoryId: "1", category: "Baked goods", product: "Aunt Hattie's", price: "375" }, { identifier: "data", categoryId: "1", category: "Baked goods", product: "Back to Nature", price: "343" }, { identifier: "data", categoryId: "2", category: "Cakes", product: "Mars Muffin (McVitie's)", price: "465" }, { identifier: "data", categoryId: "2", category: "Cakes", product: "McVitie's", price: "251" }, { identifier: "data", categoryId: "2", category: "Cakes", product: "Mr Kipling", price: "260" }, { identifier: "data", categoryId: "2", category: "Cakes", product: "Mr Kipling Frosty Fancies", price: "210" }, { identifier: "data", categoryId: "3", category: "Dairy products", product: "Amul", price: "474" }, { identifier: "data", categoryId: "3", category: "Dairy products", product: "Borden", price: "184" }, { identifier: "data", categoryId: "3", category: "Dairy products", product: "Broughton Foods Company", price: "43" }],
    i,
    l = data.length,
    hash = Object.create(null),
    categoryId, category, price;

for (i = 0; i < l; i++) {
    ({ categoryId, category, price } = data[i]);
    if (!(categoryId in hash)) {
        hash[categoryId] = { identifier: "total", categoryId, category, price: 0 };
        data.push(hash[categoryId]);
    }
    hash[categoryId].price += +price;
}

data.sort((a, b) =>
    a.categoryId - b.categoryId
        || (a.identifier === 'total') - (b.identifier === 'total')
);

console.log(data);
.as-console-wrapper { max-height: 100% !important; top: 0; }

【讨论】:

  • 非常感谢您的宝贵回答
【解决方案2】:

试试这个

var data = [
    {
        "identifier": "data",
        "categoryId": "1",
        "category": "Baked goods",
        "product": "Aunt Hattie's",
        "price": "375"
    },
    {
        "identifier": "data",
        "categoryId": "1",
        "category": "Baked goods",
        "product": "Back to Nature",
        "price": "343"
    },        
    {
        "identifier": "data",
        "categoryId": "2",
        "category": "Cakes",
        "product": "Mars Muffin (McVitie's)",
        "price": "465"
    },
    {
        "identifier": "data",
        "categoryId": "2",
        "category": "Cakes",
        "product": "McVitie's",
        "price": "251"
    },
    {
        "identifier": "data",
        "categoryId": "2",
        "category": "Cakes",
        "product": "Mr Kipling",
        "price": "260"
    },
    {
        "identifier": "data",
        "categoryId": "2",
        "category": "Cakes",
        "product": "Mr Kipling Frosty Fancies",
        "price": "210"
    },
    {
        "identifier": "data",
        "categoryId": "3",
        "category": "Dairy products",
        "product": "Amul",
        "price": "474"
    },
    {
        "identifier": "data",
        "categoryId": "3",
        "category": "Dairy products",
        "product": "Borden",
        "price": "184"
    },
    {
        "identifier": "data",
        "categoryId": "3",
        "category": "Dairy products",
        "product": "Broughton Foods Company",
        "price": "43"
    },
]

var total= 0;
var element = {};
data = data.sort((a,b)=> a.categoryId - b.categoryId)
var result = [];
data.forEach((ele,index)=>{
     
    if(!element.categoryId || element.categoryId == ele.categoryId){
        result.push(ele);
        total += parseInt(ele.price);
    }else{
      result.push({
           "identifier": "total",
           "categoryId": element.categoryId,
           "category": element.category,
           "total" : total
      });
      result.push(ele);
      total = parseInt(ele.price);  
    }
   element = ele;
})
result.push({
  identifier  :element.identifier,
  total : total
});
console.log(result);

【讨论】:

    【解决方案3】:

    您可以通过使用Array.reduce 和一个哈希对象来计算总价来实现您想要的输出:

    Stackblitz example

    【讨论】:

      【解决方案4】:

      这只是另一种解决方案。

      const result = data.sort((item1, item2) => item1.categoryId - item2.categoryId)
      .reduce((res, item) => {
          const { category, categoryId } = res.last
          const isEnd = categoryId && categoryId !== item.categoryId;
          const total = isEnd ? [{ category, categoryId, 'identifier': 'Total', 'price': res.sum }] : [];
          return {
            list: [...res.list, ...total, item],
            sum: (!isEnd ? res.sum : 0) + parseInt(item.price),
            last: item
          };
      }, { list: [], sum: 0, last: {} });
      

      查看stackblitz

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2020-05-14
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2021-06-13
        • 2019-08-27
        • 2022-01-16
        • 2022-12-10
        相关资源
        最近更新 更多