Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
3.4k views
in Technique[技术] by (71.8m points)

我想把form表单数据变成这种格式要怎么遍历呀。

我想把像是这种数据中的数组或是字符提取出来,把其中的数组下标一一对应形成一个新的对象,该怎么处理呀?我感觉我处理了个寂寞。
9f7f363d70e5e33b6eaf07f37c7da37.png
目标是变成这样子:
image.png

    // 提交
    handleSubmit() {
      const {
        form: { validateFields }
      } = this;
      validateFields((errors, values) => {
        console.log(values);
        if (!errors) {
          this.loop(values)
        }
      });
    },
    loop(tree) {
        let list = {};
        for (const prop in tree) {
          const obj = {};
          if(typeof tree[prop] === 'string'){
            list.name = tree[prop];
          } else if(prop === 'partOneLine' && Array.isArray(tree[prop])){
            tree[prop].forEach(item => {
              obj.partOneLine.push(item);
            });
            list.arr.push(obj)
          }
        }
        console.log(list)
    },

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)
loop() {
    let tree = {
      'partOneLine': ['110', '242', '142'],
      'partOneDict': ['42420', '42442', '42424'],
      'resource': 'jlfdlj'
    }
    let list = {
      arr: []
    };
    let objProps = []      // 存放对象属性的数组
    for (const prop in tree) {
      if(typeof tree[prop] === 'string'){
        list[prop] = tree[prop];
      } else if(Array.isArray(tree[prop])){
        objProps.push(prop)
      }
    }
    if (objProps[0]) {
      let length = tree[objProps[0]].length
      for (let i = 0; i< length; i++) {
        let obj = {}  
        objProps.forEach((item) => {
          obj[item] = tree[item][i]
        })
        list.arr.push(obj)
      }
    }
    console.log(list, 'list')
  },

自测能用


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...