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
1.3k views
in Technique[技术] by (71.8m points)

javascript - Create Multilevel groups from an Array of Objects

I have following type of data

data = [{
    "grp" : ["A", "B", "C"],
    "val" : [1, 2, 3]
  }, {
    "grp" : ["A", "B", "D"],
    "val" : [2, 3, 4]
  }, {
    "grp" : ["A", "C", "C"],
    "val" : [1, 3, 5]
  }, {
    "grp" : ["B", "Y", "E"],
    "val" : [1, 3, 2]
  }
]

I want to make groups like these

groups = {
  "A": {
    "B": {
      "C": [
        [1, 2, 3],
        [2, 3, 4]
      ],
      "D": [
        [1, 2, 3],
        [2, 3, 4]
      ]
    },
    "C": {
      "C": [
        [1, 3, 5]
      ]
    }
  },
  "B": {
    "Y": {
      "E": [
        [1, 3, 2]
      ]
    }
  }
}

grp array can be have maximum of 3 elements.

I tried using underscorejs something like below, however, I ended up creating individual groups, not nested groups.

var groups = _(data).reduce(function(memo, o) {
    _(o.groups).each(function(j) {
        memo[j] = memo[j] || [ ];
        memo[j].push(o);
    });
    return memo;
}, { });

Would appreciate any idea in the right direction.

See Question&Answers more detail:os

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

1 Answer

0 votes
by (71.8m points)

Try this:

var data = [{
    "grp": ["A", "B"],
    "val": [1, 2, 3]
}, {
    "grp": ["A", "B"],
    "val": [2, 3, 4]
}, {
    "grp": ["A", "C"],
    "val": [1, 3, 5]
}, {
    "grp": ["B", "Y"],
    "val": [1, 3, 2]
}]

// create an object to hold the revised structured data
var newData = {};
_.map(data, function (obj, key) {
    // check whether object is present or not
    if (_.isUndefined(newData[obj.grp[0]])) { //if object is undefined
        newData[obj.grp[0]] = {};
        newData[obj.grp[0]][obj.grp[1]] = [obj.val]; // add an array to second child of grp
    } else { // if object already exists
        // check whether second child of grp is present
        if (_.isUndefined(newData[obj.grp[0]][obj.grp[1]])) { // if not present - create an associated array
            newData[obj.grp[0]][obj.grp[1]] = [obj.val];
        } else { // if present - add value to it
            newData[obj.grp[0]][obj.grp[1]].push(obj.val);
        }
    }
});

// print on console window
console.log(newData);

JSFiddle link: http://jsfiddle.net/4G57E/


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

...