JSON rearrangement

JSON rearrangement

本文关键字:rearrangement JSON      更新时间:2023-09-26

我有下面的对象,我想重新排列它,以便传递给模板。需要帮助从以下格式转换

var nature = [
  {
    "type": "fruit",
    "name": "apple",
    "color": "red",
  },
  {
    "type": "vegetable",
    "name": "carrot",
    "color": "orange",
  },
  {
    "type": "fruit",
    "name": "grape",
    "color": "green",
  },
  {
    "type": "vegetable",
    "name": "tamato",
    "color": "red",
  },
];

转换为这种格式的

var nature = [{
    "fruit": [
        {
            "type": "fruit",
            "name": "apple",
            "color": "red"
        },
        {
            "type": "fruit",
            "name": "grape",
            "color": "green"
        }
    ],
    "vegetable": [
        {
            "type": "vegetable",
            "name": "carrot",
            "color": "orange"
        },
        {
            "type": "vegetable",
            "name": "tomato",
            "color": "red"
        }
    ]
}];

正在寻找实现它的最快方法。感谢您查看该帖子。感谢您的帮助。

对抗大自然

var goAgainstNature = function(oldNat) {
    var newNat = {}, i;
    for(i = 0; i < oldNat.length; i++) {
        (newNat[oldNat.type] = (newNat[oldNat.type] || [])).push(oldNat[i]);
    }
    return [newNat];
};

我认为这将是正确的

var goAgainstNature = function(oldNat) {
    var newNat = {}, i;
    for(i = 0; i < oldNat.length; i++) {
        (newNat["'"+oldNat[i].type+"'"] = (newNat[oldNat.type] || [])).push(oldNat[i]);
    }
    return [newNat];
};