Ramda to loop over array

后端 未结 1 2040
悲哀的现实
悲哀的现实 2021-01-29 03:40

Loop may be the wrong term, but it kind of describes what I am attempting. I want to give structure to flat data, but I also need to keep track of the array it came from.

<
1条回答
  •  迷失自我
    2021-01-29 04:06

    Something like this?

    var output = [{
      "name": "Animal",
      "typechild": [{
        "name": "Chicken",
        "level": 3
      }, {
        "name": "Dog",
        "level": 2
      }]
    }, {
      "name": "Food",
      "typechild": [{
        "name": "Chicken",
        "level": 3
      }]
    }, {
      "name": "No name",
      "typechild": [{
        "name": "Foo",
        "level": 2
      }, {
        "name": "Baz",
        "level": 2
      }]
    }]
    
    
    let out = {},
      typechild = {},
      k;
    
    const data = [{
      "title": "Test 1",
      "type": [{
        "name": "Animal",
        "level": 1
      }, {
        "name": "Food",
        "level": 1
      }, {
        "name": "Chicken",
        "level": 3
      }]
    }, {
      "title": "Test 2",
      "type": [{
        "name": "Foo",
        "level": 2
      }]
    }, {
      "title": "Test 3",
      "type": [{
        "name": "Baz",
        "level": 2
      }]
    }, {
      "title": "Test 4",
      "type": [{
        "name": "Animal",
        "level": 1
      }, {
        "name": "Dog",
        "level": 2
      }]
    }]
    
    
    data.forEach((node) => {
      k = false;
      typechild[node.title] = [];
      node.type && node.type.forEach((t, i) => {
        if (t.level == 1) {
          k = true;
    
          !out[t.name] ? out[t.name] = {
            name: t.name,
            typechild: typechild[node.title]
          } : out[t.name].typechild = out[t.name].typechild.concat(typechild[node.title]);
        } else {
          typechild[node.title].push(t);
        }
        if (i == node.type.length - 1 && !k && typechild[node.title].length) {
          out['No name'] = out['No name'] || {
            name: 'No name',
            typechild: []
          };
    
          out['No name'].typechild = out['No name'].typechild.concat(typechild[node.title]);
        }
      });
    });
    
    console.log(JSON.stringify(Object.values(out)));

    0 讨论(0)
提交回复
热议问题