使用下划线根据名称将对象属性分组为单独的较小对象

时间:2014-02-11 21:10:32

标签: javascript underscore.js

目前我有一个对象有多个以“_id(实际上是数字)”为前缀的键,如下所示:

    var obj = {
outFieldType_25669: "Select a type"
outFieldType_97327: "Select a type"
outfieldWallType_25669: "Select a type"
outfieldWallType_97327: "Select a type"

scoreboardDetailsShown_25669: "e.g. players name, photo, stats, etc..."
scoreboardDetailsShown_97327: "e.g. players name, photo, stats, etc..."
scoreboardOperatedBy_25669: "Select a type"
scoreboardOperatedBy_97327: "Select a type"

warningTrackType_25669: "Select a type"
warningTrackType_97327: "Select a type"
};

我想要做的是将该对象拆分为按结束前缀分组的较小对象,这是设想结果的示例:

objA = {
    outFieldType_97327: "Select a type",
    outfieldWallType_97327: "Select a type",
    scoreboardDetailsShown_97327: "e.g. players name, photo, stats, etc..."
    scoreboardOperatedBy_97327: "Select a type",
    warningTrackType_97327: "Select a type"
};

objB = {
   outFieldType_25669: "Select a type",
   outfieldWallType_25669: "Select a type",
   scoreboardDetailsShown_25669: "e.g. players name, photo, stats, etc...",
   scoreboardOperatedBy_25669: "Select a type",
   warningTrackType_25669: "Select a type"
};

1 个答案:

答案 0 :(得分:1)

使用_.each迭代对象,split来自密钥的id并将其存储在单独的对象中,例如

var sorted = {};

var obj = {
    outFieldType_25669: "Select a type",
    outFieldType_97327: "Select a type",
    outfieldWallType_25669: "Select a type",
    outfieldWallType_97327: "Select a type",
    scoreboardDetailsShown_25669: "e.g. players name, photo, stats, etc...",
    scoreboardDetailsShown_97327: "e.g. players name, photo, stats, etc...",
    scoreboardOperatedBy_25669: "Select a type",
    scoreboardOperatedBy_97327: "Select a type",
    warningTrackType_25669: "Select a type",
    warningTrackType_97327: "Select a type"
};

_.each(obj, function (value, key) {
    var id = key.split("_")[1];
    if (sorted[id] === undefined) {
        sorted[id] = {}
    };
    sorted[id][key] = value;
});

console.log(sorted);

请参阅此JSFiddle