Добавить поле в JSON не в интерфейсе Vuejs - PullRequest
1 голос
/ 08 мая 2020

Я использую vue / cli 4.3.1 vue: 2.6.11

У меня есть массив в json, и я хочу добавить в него значение в зависимости от значения в другом поле. например:

"rules":[{"id":1,"name":"new rule","patient":[],"code":[1],"to_code":[1]}]

если массив кода содержит индекс значения кода == 50, то to_code содержит индекс значения кода 100, иначе to_code пуст в этом коде правила:

 {"code":[{"id":1,"name":"New Item","values":[{"id":1,"code":"50"}]}]
to_code:
"to_code":[{"id":1,"name":"To code 100","values":100}

данные в JSON собираются в этой функции:

  saveData() {

      let params = {
        data: {
          code: this.codeList,

          to_code: this.toCodeList

          rules: this.pacList
        }
      };

состояние в vuex:

   toCodeList: state => state.to_codes,
codeList: state => state.codes,

save Vue Store (Local) в этой функции:

  saveRule() {

      if (this.ruleItem.id > 0) {
        console.log(this.ruleItem);
      } else {
        let newId = 1;
        if (this.pacList.length > 0) {
          newId =
            Math.max.apply(
              Math,
              this.pacList.map(function(o) {
                return o.id;
              })
            ) + 1;
        }

        this.ruleItem.id = newId;

        this.pacList.push(this.ruleItem);
      }

функция создания нового правила:

   createRule() {

      this.ruleItem = { ...this.emptyRule };

пустое правило:

 emptyRule: {
      id: 0,
      name: "new rule",
      code: [],
      to_code:[]
}

что я пытался сделать в функции saveRule:


      var parsedobj = JSON.parse(JSON.stringify(this.codeList));

      parsedobj.forEach(arrayItem => {
        var x = arrayItem.values;
        for (let item = 0; item < x.length; item++) {
          const element = x[item].id;
          const codenumber = x[item].code;
          if (codenumber == 50 || codenumber == 200) {
            let correctID = x[item].id;

            var parsepaclist = JSON.parse(JSON.stringify(this.pacList));

            parsepaclist.forEach(pacitem => {
              for (let index = 0; index < parsepaclist.length; index++) {
                const IDofpaclist = parsepaclist[index].id;
                const Itemofpaclist = parsepaclist[index];

                var numberofDestPort = pacitem.code;

                if (correctID == Itemofpaclist.code) {
                  if (codenumber == 50) {
                    let newtocode = {
                      id: 1,
                      name: "To code 100",
                      values: 100,
                      active: false
                    };
                    this.tocodelist.push(newtocode);

                    Itemofpaclist.to_code.push(1);

                    if (Itemofpaclist.id == this.ruleItem.id) {
                      this.ruleItem.to_code = Itemofpaclist.to_code;
                    }
                  } else if (codenumber == 200) {
                    let newtocode = {
                      id: 2,
                      name: "To Code 300",
                      values: 300,
                      active: false
                    };
                    this.tocodelist.push(newtocode);

                    Itemofpaclist.to_code.push(2);
                    if (Itemofpaclist.id == this.ruleItem.id) {
                      this.ruleItem.to_code = Itemofpaclist.to_code;
                    }
                  }
                }
              }
            });
          }
        }
      });

проблема в том, что когда я добавляю объект toCode кода 50 в Json, не содержит индекса для значения кода 100 или в объекте toCode кода 200 в Json не содержит индекса для значения кода 300

1 Ответ

0 голосов
/ 11 мая 2020
    new Vue({
    el: '#content',
    data: {
      code: {},
      to_code: {},
      rule: {}
    },
    created: function () {
      this.code = Object.assign({"code":[{"id":1,"name":"New Item","values":[{"id":1,"code":"50"}]}]})
      this.to_code = Object.assign({"to_code":[{"id":1,"name":"To code 100","values":100}]})
      // this.rule = 

      for (var i = this.code.code.length - 1; i >= 0; i--) {

        var code = this.code.code[i]['values']

        for (var k = code.length - 1; k >= 0; k--) {

          if (code[k]['code'] == 50) {

            for (var j = this.to_code.to_code.length - 1; j >= 0; j--) {

              var to_code = this.to_code.to_code[j]['values']

              if (to_code == 100) {
                this.rule = Object.assign({"rules":[{"id":1,"name":"new rule","patient":[],"code": this.code.code[i],"to_code":this.to_code.to_code[j]}]})
              }
            }

          } else {
            this.rule = Object.assign({"rules":[{"id":1,"name":"new rule","patient":[],"code": this.code.code[i],"to_code":[]}]})
          }

        };

      };
      console.log(JSON.stringify(this.rule))
    }
  })

Вы можете установить свои требования и код в этой структуре кодирования. Спасибо.

Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...