如何遍历对象数组以求和

时间:2018-07-04 11:23:34

标签: javascript jquery arrays json

我的对象数组如下:

[
  {
    "id": "0",
    "title": "Exercise",
    "main_object": {
      "title": "Exercise",
      "number1": {
        "1": "10",
        "2": "10",
        "3": "5",
        "4": "20",
      },
      "sumtype": {
        "1": "+",
        "2": "-",
        "3": "x",
        "4": ":",
      },
      "number2": {
        "1": "10",
        "2": "5",
        "3": "2",
        "4": "2",
      }
    }
  }
]

现在我将如何使用它在javascript中创建一个数组(如果有更简单的方法,可以在jquery中创建一个数组),该数组具有这些简单总和的答案。因此,数组中的第一个字符串将为10 + 10,即为20。第二个字符串应为10-5,即为5。

我使用$ .getJSON检索我的JSON,并尝试了一个简单的for循环,如下所示:

var sumanswers = [];
var keyamount = Object.keys(exerSumType);
var keylength = keyamount.length;
for (i = 0; i < keylength; i++) {
    sumanswers[i] = exerNumber1[i] + exerSumType[i] + exerNumber2[i];
}

这只是给我一个字符串形式的总和(例如“ 10 + 10”),而我要为“ 20”。除此之外,由于某种原因,这并不能给我所有的总和,在我console.log(sumanswers):

0: NaN
1: "10+10"
2: "10-5"
3: "5x2"

因此,我由于某种原因而错过了我的最后一笔款项,而将NaN作为首笔款项。

任何帮助将不胜感激!

var exercises = [{
  "id": "0",
  "title": "Exercise",
  "main_object": {
    "title": "Exercise",
    "number1": {
      "1": "10",
      "2": "10",
      "3": "5",
      "4": "20",
    },
    "sumtype": {
      "1": "+",
      "2": "-",
      "3": "x",
      "4": ":",
    },
    "number2": {
      "1": "10",
      "2": "5",
      "3": "2",
      "4": "2",
    }
  }
}]

var sumanswers = [];
var keyamount = Object.keys(exerSumType);
var keylength = keyamount.length;
for (i = 0; i < keylength; i++) {
  sumanswers[i] = exerNumber1[i] + exerSumType[i] + exerNumber2[i];
  console.log(sumanswers[i] , exerNumber1[i] , exerSumType[i] , exerNumber2[i])
}

5 个答案:

答案 0 :(得分:4)

您可以将数组用于可枚举数据。数组基于零,因此索引从零开始。

要使用给定的操作数来计算某些值,可以将所有操作数作为键的对象。

var data = [{ id: "0", title: "Exercise", main_object: { title: "Exercise", number1: { "1": "10", "2": "10", "3": "5", "4": "20" }, sumtype: { "1": "+", "2": "-", "3": "x", "4": ":" }, number2: { "1": "10", "2": "5", "3": "2", "4": "2" } } }],
    op = {
        '+': (a, b) => +a + +b,
        '-': (a, b) => a - b,
        'x': (a, b) => a * b,
        ':': (a, b) => a / b
    };

data.forEach(({ main_object }) => {
    main_object.answers = {};
    var { answers, number1, number2, sumtype } = main_object;
    Object
        .keys(main_object.number1)
        .forEach(k => answers[k] = op[sumtype[k]](number1[k], number2[k]))
});

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

答案 1 :(得分:0)

您可以使用json_encode()函数对其进行翻译。 例如;

$veri .= array();
$veri .= array();
json_encode($veri);

答案 2 :(得分:0)

这是起诉 ES6 的有效代码段; template<class T, class D> struct can_convert_to { private: template<typename U> static auto check(U* t) -> decltype( static_cast<D>(*t), std::true_type()); template<typename U> static std::false_type check(...); public: static constexpr bool value = std::is_same<decltype(check<T>(nullptr)), std::true_type>::value; }; Object.keysArray.reduceSpread operator

Dynamic key name

答案 3 :(得分:0)

   var test = [
          {
            "id": "0",
            "title": "Exercise",
            "main_object": {
              "title": "Exercise",
              "number1": {
                "1": "10",
                "2": "10",
                "3": "5",
                "4": "20",
              },
              "sumtype": {
                "1": "+",
                "2": "-",
                "3": "x",
                "4": ":",
              },
              "number2": {
                "1": "10",
                "2": "5",
                "3": "2",
                "4": "2",
              }
            }
          }
        ]



        var test = [
          {
            "id": "0",
            "title": "Exercise",
            "main_object": {
              "title": "Exercise",
              "number1": {
                "1": "10",
                "2": "10",
                "3": "5",
                "4": "20",
              },
              "sumtype": {
                "1": "+",
                "2": "-",
                "3": "x",
                "4": ":",
              },
              "number2": {
                "1": "10",
                "2": "5",
                "3": "2",
                "4": "2",
              }
            }
          }
        ]

        test.forEach(ele=> {
        for (let index in ele.main_object.number1){

            var text = ele.main_object;
             var num1  = text.number1[index];
             var op = text.sumtype[index];
             op = op === 'x' ? "*" : op
            op = op === ':' ? "/" : op
             var num2 = text.number2[index];
              console.log(num1 + text.sumtype[index] + num2 +'=' + eval(num1 + op + num2))

        }

        })

答案 4 :(得分:-1)

Eval赢了!

使用eval(string)来执行字符串,就好像它是普通的旧JavaScript一样

sumanswers.map(sumanswer => eval(sumanswer))

https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/eval