动态生成json属性值

时间:2014-08-25 07:03:32

标签: javascript arrays json dynamic

我有一个json对象如下:

{
    "critiquesAvg": 4.75: , 
    "critiques":[
        {
            'author': 'John Does',
            'comment': "I like it",
            'stars' : 5
        },
        {
            'author': 'Jacob Works',
            'comment': "I like it too",
            'stars' : 4.5
        }
    ]
}

我需要通过平均批点数组的critiquesAvg属性值来动态计算stars的值(4.75)。

有人可以帮我吗?

修改 道歉,我遇到的实际问题如下:

var dealers = [{
    "id", 1874
    "critiquesAvg": 4.75 ,
    "critiques":[
        {
            'author': 'John Does',
            'comment': "I like it",
            'stars' : 5
        },
        {
            'author': 'Jacob Works',
            'comment': "I like it too",
            'stars' : 4.5
        }
    ]
},
{
    "id": 1345,
    "critiquesAvg": 5 ,
    "critiques":[
        {
            'author': 'John Does',
            'comment': "I like it",
            'stars' : 5
        },
        {
            'author': 'Jacob Works',
            'comment': "I like it too",
            'stars' : 5
        }
    ]
}
];

在这里,我想根据特定经销商数据的平均评分数动态计算critiquesAvg属性的值。

4 个答案:

答案 0 :(得分:3)

我会使用reduce(小提琴here):

var data = {
    "critiquesAvg": 4.75, 
    "critiques":[
        {
            'author': 'John Does',
            'comment': "I like it",
            'stars' : 5
        },
        {
            'author': 'Jacob Works',
            'comment': "I like it too",
            'stars' : 4.5
        }
    ]
};

var sum = data.critiques.reduce(function(x, y) { return x.stars + y.stars });
var average = sum / data.critiques.length;

data.critiquesAvg = average;

至于更新后的问题,您需要添加额外的循环,例如使用forEach(更新的小提琴here):

dealers.forEach(function(data) {
    var sum = data.critiques.reduce(function(x, y) { return x.stars + y.stars });
    var average = sum / data.critiques.length;

    data.critiquesAvg = average;
});

答案 1 :(得分:2)

您可以通过以下函数替换critiquesAvg来执行此操作:

critiquesAvg: function(){
    var stars = 0;
    for(i=0;i<this.critiques.length;i++) {
        stars +=this.critiques[i].stars;
    }
    return stars/this.critiques.length
}, 

检查script.js这个plunker: http://plnkr.co/edit/dDxkZxKxvq0HRppASnzR?p=preview

答案 2 :(得分:1)

Robby做到了,我想我会把它扩展到一个函数

function dataGen(data){
    //so we do not overwrite data globally as objects are references
    var data = data;
    var sum = data.critiques.reduce(function(x, y) {
        return x.stars + y.stars 
    });
    var average = sum / data.critiques.length;

    data.critiquesAvg = average;
    return data;
}

var data = { 
    "critiques":[
        {
            'author': 'John Does',
            'comment': "I like it",
            'stars' : 5
        },
        {
            'author': 'Jacob Works',
            'comment': "I like it too",
            'stars' : 4.5
        }
    ]
};

data.critiques.push({
    'author': 'Wacob Works',
    'comment': "I like it too",
    'stars' : 3.5
});

data = dataGen(data);

确定更新了您的要求,希望这有助于http://jsbin.com/sevor/1/edit

var dealers = [{
  "id": 1874,
    "critiquesAvg": 0 ,
    "critiques":[
        {
            'author': 'John Does',
            'comment': "I like it",
            'stars' : 5
        },
        {
            'author': 'Jacob Works',
            'comment': "I like it too",
            'stars' : 4.5
        }
    ]
},
{
    "id": 1345,
    "critiquesAvg": 5 ,
    "critiques":[
        {
            'author': 'John Does',
            'comment': "I like it",
            'stars' : 5
        },
        {
            'author': 'Jacob Works',
            'comment': "I like it too",
            'stars' : 5
        }
    ]
}
];

var Dealers = {
    calculate: function(dealer){
        var sum = dealer.critiques.reduce(function(x, y) {
            return x.stars + y.stars; 
        });
        var average = sum / dealer.critiques.length;
        return average;
    },
    gen: function(dealers){
        for(i=0;i<dealers.length;i++){
            dealers[i].critiquesAvg = this.calculate(dealers[i]);
        }

        return dealers;
    }
};

dealers = Dealers.gen(dealers);

dealers.push({
    "id": 1346,
    "critiquesAvg": 0 ,
    "critiques":[
        {
            'author': 'John Does',
            'comment': "I like it",
            'stars' : 5
        },
        {
            'author': 'Jacob Works',
            'comment': "I like it too",
            'stars' : 5
        }
    ]
});

dealers = Dealers.gen(dealers);
console.log(dealers);

答案 3 :(得分:1)

向对象添加init函数,并在其中进行所有计算。 如果你看一下其他面向对象的语言,通常你会在构造函数中进行这种计算。类似地,你可以用自定义方法实现相同的方法,它可以作为构造函数并设置初始的状态你的对象。

var obj = ({
  "critiquesAvg": 0, //start with zero and init function will calculate the actual avg
  "critiques": [{
    'author': 'John Does',
    'comment': "I like it",
    'stars': 5
  }, {
    'author': 'Jacob Works',
    'comment': "I like it too",
    'stars': 4.5
  }],
  init: function() {
    var result = this.critiques.reduce(function(prev, current, idx, arr) {
      return prev['stars'] + current['stars'];
    });
    this.critiquesAvg = result / this.critiques.length;
    return this;
  }
}).init(); // you are invoking the init method inline here (coding pattern)
           // also watch out for the ( ) around the object literal. 
           // this is what makes the method on the object invokable inline.

这是一种编码模式,通常用于设置对象状态(尤其是在javascript中使用对象文字语法时)。

DEMO

更新回答

遵循相同的模式,但不是每个都有一个init方法,一个常见的初始化方法将执行相同的操作。

var initialize = function() {
  var result = this.critiques.reduce(function(prev, current, idx, arr) {
    return prev['stars'] + current['stars'];
  });
  this.critiquesAvg = result / this.critiques.length;
  return this;
};

var dealers = [({
  "id": 1874,
  "critiquesAvg": 0,
  "critiques": [{
    'author': 'John Does',
    'comment': "I like it",
    'stars': 5
  }, {
    'author': 'Jacob Works',
    'comment': "I like it too",
    'stars': 4.5
  }],
  init: initialize
}).init(), ({
  "id": 1345,
  "critiquesAvg": 0,
  "critiques": [{
    'author': 'John Does',
    'comment': "I like it",
    'stars': 5
  }, {
    'author': 'Jacob Works',
    'comment': "I like it too",
    'stars': 5
  }],
  init: initialize
}).init()];

DEMO