如何在json stringify输出中获取特定对象?

时间:2017-07-27 23:52:46

标签: javascript arrays json

任何人都可以帮我解决如何在json中获取特定对象的问题吗?

我只想总结stringify输出中的所有3个。



var arr_question = [{"$1z_1":3,"$2o_1":"Question 1."},{"$1z_1":3,"$2o_1":"Question2."},{"$1z_1":3,"$2o_1":"Question3."}];

console.log("output: "+arr_question.$1z_1);
console.log("arrays: "+arr_question)




2 个答案:

答案 0 :(得分:3)

你有一个对象数组。您需要遍历数组,访问属性并添加它们。一种选择是使用reduce方法:



var arr_question = [{"$1z_1":3,"$2o_1":"Question 1."},{"$1z_1":3,"$2o_1":"Question2."},{"$1z_1":3,"$2o_1":"Question3."}];

console.log(
  "output: " +
  arr_question.reduce((sum, obj) => sum + obj.$1z_1, 0)
);




答案 1 :(得分:1)

您可以使用forEach迭代数组,并将数组中每个对象的值添加到先前声明的“total”变量中,该变量是所有值的总和。

var arr_question = [{"$1z_1":3,"$2o_1":"Question 1."},{"$1z_1":3,"$2o_1":"Question2."},{"$1z_1":3,"$2o_1":"Question3."}];

var total = 0;
arr_question.forEach(function(obj){
  total += obj.$1z_1;
 })

console.log("output: " + total); // gives "output: 9"