假设,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.
有什么想法吗?
答案 0 :(得分:1)
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]);
}
Object.assign()
。它用于克隆或修改原始对象到目标对象
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
}
}