目前我有一个对象有多个以“_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"
};
答案 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。