我有一个这样的对象:
myObject = {
"member.1": "98bbe8c6-48db-990eeec325"
"member.2": "cc0419d3-6c97-xcd32d3ba6"
"member.3": "dba16933-b972-34fee1fefc"
"member.4": "bb32b6e7-1ac2-a687295acb"
"member.5": "a4fe92cf-2640-8f77d2c44e"
"member.6": "b2e9b23c-3dab-3fba8195b3"
}
我希望能够将它拆分为更小的对象,就像我使用splice方法将数组拆分为子数组一样。
myObject1 = {
"member.1": "98bbe8c6-48db-990eeec325"
"member.2": "cc0419d3-6c97-xcd32d3ba6"
}
myObject2 = {
"member.3": "dba16933-b972-34fee1fefc"
"member.4": "bb32b6e7-1ac2-a687295acb"
}
myObject2 = {
"member.5": "a4fe92cf-2640-8f77d2c44e"
"member.6": "b2e9b23c-3dab-3fba8195b3"
}
有没有办法做到这一点?
答案 0 :(得分:0)
您必须迭代属性并将每个N属性分配给新对象:
function splitProperties(myObject, propsPerObject) {
var propCntr = 0;
var currentObj = {};
var newObjects = [];
for (var prop in myObject) {
if (propCntr >= propsPerObject) {
newObjects.push(currentObj);
currentObj = {};
propCntr = 0;
}
currentObj[prop] = myObject[prop];
++propCntr;
}
newObjects.push(currentObj);
return newObjects;
}
var smallerObjects = splitProperties(myObject, 2);
这会创建一个新对象数组,每个对象都有propsPerObject
属性(如果总属性数不能被整除,则最后一个对象可能会有更少的属性。)
答案 1 :(得分:0)
underscore.js有一个方便的pick(obj, *keys)
函数,在写出时看起来像这样:
_.pick = function(obj) {
var copy = {};
var keys = concat.apply(ArrayProto, slice.call(arguments, 1));
each(keys, function(key) {
if (key in obj) copy[key] = obj[key];
});
return copy;
};
您将使用myObject1 = _.pick(myObject, 'member.1', 'member.2')
调用它,它将返回仅包含所选属性的myObject
副本。如果你想在不使用underscore.js的情况下使用它,我建议在普通的Javascript中实现这样的东西。