假设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.
有什么想法吗?
发布于 2018-05-30 09:56:50
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
}
}
https://stackoverflow.com/questions/50595227
复制相似问题