在javascript中的Object.assign(object1 [i])

时间:2018-05-30 01:39:55

标签: javascript javascript-objects

假设,object1有10个对象。 此代码将object1分配给object2

const object2 = Object.assign(object1);

但我想只使用for循环从object1分配5个对象。

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

有什么想法吗?

1 个答案:

答案 0 :(得分:1)

  1. 我假设obj1和obj2都是数组
  2. 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. 我假设你正在学习Object.assign()。它用于克隆或修改原始对象到目标对象
    2.     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
              }
          }