-1

テンプレートに渡すことができるように再配置したい次のオブジェクトがあります。次の形式から変換するためのヘルプが必要です

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"
        }
    ]
}];

それを達成するための最速の方法を探しています。投稿を見ていただきありがとうございます。助けに感謝します。

4

2 に答える 2

1

これは正しいと思います

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];
};
于 2012-09-07T14:59:27.463 に答える
1

自然と戦え!

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];
};
于 2012-09-07T14:41:07.413 に答える