假设我有两个数组...
import { Component, OnInit } from '@angular/core';
import { CommonserviceService } from './../utilities/services/commonservice.service';
import { FormGroup, FormControl } from '@angular/forms';
@Component({
selector: 'app-home',
templateUrl: './home.component.html',
styleUrls: ['./home.component.css']
})
export class HomeComponent implements OnInit {
getListData: any;
dataGroup: FormGroup;
selectedGroups: string[];
constructor(private commonserviceService: CommonserviceService) {
this.dataGroup = new FormGroup({
email: new FormControl(''),
password: new FormControl(''),
list: new FormControl('')
});
this.selectedGroups = [];
}
ngOnInit() {
}
onCheckChange(event) {
if (event.target.checked) {
this.selectedGroups.push(event.target.value);
} else {
const index = this.selectedGroups.findIndex(item => item === event.target.value);
if (index !== -1) {
this.selectedGroups.splice(index, 1);
}
}
}
getFormData(value){
value['groups'] = this.selectedGroups;
console.log(value);
}
}
我知道我可以使用嵌套的for循环将'age'对象设置为array2中的值。但是,使用诸如find或map之类的javascript方法还有另一种方法吗?因此理想的结果将是...
df1['C']=df2.C.reindex(df1.index.get_level_values(0)).values
df1
A B C
bar one -0.007969 0.754405 -0.137703
two -0.690867 -0.223325 -0.137703
baz one 1.490032 -2.207812 -1.145512
two 1.428660 -0.982451 -1.145512
foo one -1.203488 -2.190912 NaN
two -0.791889 -0.199983 NaN
还有什么是array2 ...
array1 = [{'age':'', 'name':'John'}, {'age':'', 'name':'Mark'}, {'age':'', 'name':'Curtis'}]
array2 = ['23','25','29']
即使对象名称不同,我也可以做同样的事情吗?谢谢。
答案 0 :(得分:1)
使用Array.map()
,并使用索引(age
)从第一个数组中提取i
,并使用对象解构进行合并:
const array1 = [{'age':'', 'name':'John'}, {'age':'', 'name':'Mark'}, {'age':'', 'name':'Curtis'}]
const array2 = ['23','25','29']
const result = array1.map((o, i) => ({ ...o, age: array2[i] }))
console.log(result)
处理array2
的第二版是类似的,使用索引并取值:
const array1 = [{'age':'', 'name':'John'}, {'age':'', 'name':'Mark'}, {'age':'', 'name':'Curtis'}]
array2 = [{'value':'23'},{'value':'25'},{'value':'29'}]
const result = array1.map((o, i) => ({ ...o, age: array2[i].value }))
console.log(result)