【问题标题】:JSON Adding unique key valuesJSON 添加唯一键值
【发布时间】:2017-01-22 22:55:05
【问题描述】:

我正在尝试在我想要的输出中添加下面小提琴的唯一值

  { category: 'fos', value: 70 },
    { category: 'nyedva', value: 30 }

我能够获取数组中的唯一值,但不确定在哪里添加值

http://jsfiddle.net/mj3q0sk3/

var catalog={
    products : [
        { category: 'fos', value: 10 },
        { category: 'fos', value: 20 },
        { category: 'nyedva', value: 30 },
        { category: 'fos', value: 40 },
    ]
};
var categories = [];
var sum=[];

$.each(catalog.products, function(index, value) {
    if ($.inArray(value.category, categories)==-1) {
        categories.push(value.category);
    }
    else {
            console.log("CAt Val:" +value.category);
            var total=value.value;
        sum.push(total);
    }

});

console.log(categories);
console.log(sum);

【问题讨论】:

    标签: javascript jquery html css json


    【解决方案1】:

    您可以使用forEach() 循环返回所需的结果。

    var catalog = {"products":[{"category":"fos","value":10},{"category":"fos","value":20},{"category":"nyedva","value":30},{"category":"fos","value":40}]}
    
    var result = [];
    catalog.products.forEach(function(e) {
      var c = e.category;
      !this[c] ? (this[c] = e, result.push(this[c])) : this[c].value += e.value
    }, {})
    
    console.log(result)

    【讨论】:

      【解决方案2】:

      你可以在不需要 jQuery 的情况下做到这一点:

      var res = catalog.products.reduce(function(res, product) {
        if (!res.hasOwnProperty(product.category)) {
          res[product.category] = 0;
        }
        res[product.category] += product.value;
        return res;
      }, {});
      
      console.log(res);
      

      这产生:

      { fos: 70, nyedva: 30 }
      

      如果你想要它作为一个类别数组:

      console.log(Object.keys(res).map(function(key) { return { category: key, value: res[key] }; }));
      

      这会给你:

      [ { category: 'fos', value: 70 },
        { category: 'nyedva', value: 30 } ]
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2019-04-02
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2020-11-09
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多