Search code examples
javascriptjavascript-objects

Object.assign(object1[i]) in javascript


Let say, object1 has 10 objects. And this code assigns object1 to object2

const object2 = Object.assign(object1);

But I want to assign 5 objects only from object1 using for loop.

for (let i = 0; i < 5; i++) {
    object2 = Object.assign(object1[i]);
}
// but this one won't work.

Any ideas?


Solution

    1. I am assuming both obj1 and obj2 are arrays

    var obj1 = []
        for (let i=0; i< 10; i++)
        {
            obj1.push({key: i});
        }
        var obj2 = []
        for (let i=0; i< 5; i++)
        {
            obj2.push(obj1[i]);
        }

    1. I am assuming you're learning Object.assign(). It is used to clone or modify original object to target object

        var obj1 = {key:1, foo: 'bar'};
        var obj2 = Object.assign({}, obj1);    //clone all properties
        var obj3 = Object.assign({foo: 'not bar', newprop: 'anything'}, obj1);    //copy the original, modify `foo` property and add `newprop`
        //you can iterate through properties with this
        for (var property in obj3) {
        if (obj3.hasOwnProperty(property)) {
              // do stuff, may be filter which property you want to get, etc
            }
        }