我需要将数组推送到无法执行此任务的对象内的对象。我正在研究 Angular 6
这是一个示例。
abc = { data: { name: '', version: '', type: '', ports: [], vm:[] } };
let hostlist = ['1234.Vm', '5678.Vm', '6789.Vm'];
//Need to push hostlist data to adc.data.vm
this.adc.data.vm.push(hostlist);
//this output is array inside array
this.adc.data.vm.concat(hostlist);
// concat cont work gives empty array
我需要这种格式的输出
{ name: '', version: '', type: '', ports: [], vm:['1234.Vm', '5678.Vm', '6789.Vm'] }
最佳答案
您可以使用扩展运算符push
或将adc.data.vm
重新分配给concat
的结果 (因为 concat
返回一个新数组而不更改现有数组):
方法1:使用展开运算符的push()
// method 1: push with spread operator
let adc = {
data: {
name: '',
version: '',
type: '',
ports: [],
vm: []
}
};
let hostlist = ['1234.Vm', '5678.Vm', '6789.Vm'];
adc.data.vm.push(...hostlist);
console.log(adc);
方法二:重新赋值给concat的结果
let adc = {
data: {
name: '',
version: '',
type: '',
ports: [],
vm: []
}
};
let hostlist = ['1234.Vm', '5678.Vm', '6789.Vm'];
adc.data.vm = adc.data.vm.concat(hostlist);
console.log(adc);
关于javascript - 需要将数组推送到对象,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/53200834/