need to push an array to an object

4172 views javascript
6

I need to push array to an object inside an object not able to perform this task. I am working on angular 6

Here is an example.

 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

I need the output in this format

{ name: '', version: '', type: '', ports: [], vm:['1234.Vm', '5678.Vm', '6789.Vm'] }

answered question

3 Answers

10

You can either push with the spread operator or reassign adc.data.vm to the result of concat (since concat returns a new array):

// 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);

// method 2: reassign to result of concat
adc = {
  data: {
    name: '',
    version: '',
    type: '',
    ports: [],
    vm: []
  }
};
adc.data.vm = adc.data.vm.concat(hostlist);
console.log(adc);

posted this
9

You could always assign the object to that property:

abc.data.vm = abc.data.vm.concat(['1234.Vm', '5678.Vm', '6789.Vm']);

posted this
11

Change adc to abc adc is not defined.

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.abc.data.vm.push(hostlist);
//this output is array inside array
this.abc.data.vm.concat(hostlist);
// concat cont work gives empty array

posted this

Have an answer?

JD

Please login first before posting an answer.