如何添加两个键值并使用javascript在json中动态显示另一个键值

时间:2016-09-30 09:07:44

标签: javascript json node.js

我有以下json

var data = {
    "total": "",
    "scores": [{
        "subject": "maths",
        "marks": "50"
    }, {
        "subject": "science",
        "marks": "75"
    }]
};

现在总数中,值应为125,应自动更新。 同样在分数键中,值将动态变化。因此,所有标记应自动添加并总计显示。 那么我怎么能用任何javascript做到这一点。 有人能帮我吗。 谢谢!

预期

var data = {
    "total": "125",
    "scores": [{
        "subject": "maths",
        "marks": "50"
    }, {
        "subject": "science",
        "marks": "75"
    }]
};

5 个答案:

答案 0 :(得分:2)

您可以使用reduce()计算总数,然后将其分配给data.total

var data = {
  "total": "",
  "scores": [{
    "subject": "maths",
    "marks": "50"
  }, {
    "subject": "science",
    "marks": "75"
  }]
}

var total = data.scores.reduce(function(a, b) {
  return a + parseInt(b.marks);
}, 0)

data.total = total;
console.log(data)

答案 1 :(得分:1)

您可以应用getter并从分数中减少值。



var data = {
        get total() {
            return this.scores.reduce(function (r, a) { return r + +a.marks; }, 0)
        },
        scores: [{ subject: "maths", marks: "50" }, { subject: "science", marks: "75" }]
    };

console.log(data.total);




答案 2 :(得分:0)

您可以实现自己的类:

function Data()
{
    this.scores = [];
    this.total = 0;

    this.addScore = function(subject ,marks) {
        var score = { "subject" : subject ,"marks" : marks };

        this.scores.push(score);
        this.total += marks;
    }

    this.stringify = function() {
        return JSON.stringify(this);
    }
}

var data = new Data();

data.addScore("maths",50);
console.log( data.stringify() );
data.addScore("science",75);
console.log( data.stringify() );

输出:

{"scores":[{"subject":"maths","marks":50}],"total":50}
{"scores":[{"subject":"maths","marks":50},{"subject":"science","marks":75}],"total":125}

您可以使用,对象本身或JSON字符串。希望有所帮助...

答案 3 :(得分:0)

一个简单的for循环就足够了。

let data = {
  "total": "",
  "scores": [{
    "subject": "maths",
    "marks": "50"
  }, {
    "subject": "science",
    "marks": "75"
  }]
};

for (let i in data.scores)
  data.total = ((parseInt(data.total) || 0) + parseInt(data.scores[i].marks)).toString();

console.log(data)

答案 4 :(得分:-1)

这是ES 2015解决方案:

var result = 0;

for (let score of data.scores){
    result += parseInt(score.marks);
}

data.total = result;

使用较旧的JavaScript

可以实现同样的目标
result = 0;

for(var i = 0; i < data.scores.length; i++) {
    result += parseInt(data.scores[i].marks);
}

data.total = result;

您应该能够将此代码段放入代码中。请记住不要使用for .. in,因为https://developer.mozilla.org/de/docs/Web/JavaScript/Reference/Statements/for_each...in

已弃用

希望我能帮忙

编辑:似乎有一个关于for ...的其他MDM页面,它没有被声明为已弃用。对此感到抱歉。