Skip to content
Advertisement

Move specific properties from object to object

I have an object with a lot of properties, lets say:

obj1={a:1, b:2,..., z:-1};

I want to separate a group of properties as follow:

obj2={a:1, h:25, w:3};
obj3={rest of properties};

What i am doing is:

const {a,h,w,...obj3} = obj1;
const obj2={a,h,w};

is this the only way to achive this? is there a way to ignore properties that are undefined? For example let say h is undefined, so ideally obj2 would only be obj2={a,w} It is possible that in the future obj1 will grow and that means i will have to add the new properties in both lines of my approach.

Advertisement

Answer

It’s not the only way, but the other ways have the same problem that you noted: You have to code the property names, and so if you add more properties later, you have to add those. Either way, you have to have a list of either A) the properties you want in obj2 or B) the properties you want in obj3.

Just for illustration, here’s one other way, but I’m not saying it’s at all better:

const obj1 = {a: 1, b: 2, h: 8, w: 23, x: 24, c: 3};
// Your original code:
function original() {
    const {a,h,w,...obj3} = obj1;
    const obj2={a,h,w};
    console.log("obj2", obj2);
    console.log("obj3", obj3);
}
original();

// Another way to do it, but still has the same problem
function alternative() {
    const obj2props = new Set(["a", "h", "w"]);
    const obj2 = {};
    const obj3 = {};
    for (const key of Object.keys(obj1)) {
        const target = obj2props.has(key) ? obj2 : obj3;
        target[key] = obj1[key];
    }
    console.log("obj2", obj2);
    console.log("obj3", obj3);
}
alternative();
.as-console-wrapper {
    max-height: 100% !important;
}
User contributions licensed under: CC BY-SA
3 People found this is helpful
Advertisement