javascriptarraysobjectdata-structuresdestructuring

How to split a single-object array-item into an array of three objects?


Given is the response data's following data structure ...

const res = {
  data: [{
    name: 'c2',
    ipaddr: '192.168.1.5',
    port: 4435,
    sshuser: "abc",
    sshpass: "xyz",
    sshport: 22,
    license: 'license.txt',
  }],
};

I want to convert it to ...

const newState = [{
  name: 'c2',
  ipaddr: '192.168.1.5',
  port: 4435,
}, {
  sshuser: "abc",
  sshpass: "xyz",
  sshport: 22,
}, {
  license: 'license.txt',
}]

The below posted code does achieve the expected result ...

var obj1 = {
  name: res.data[0].name,
  ipaddr: res.data[0].ipaddr,
  port: res.data[0].port,
};
var obj2 = {
  sshuser: res.data[0].sshuser,
  sshpass: res.data[0].sshpass,
  sshport: res.data[0].sshport,
};
var obj3 = {
  license: res.data[0].license,
};
const newState = [obj1, obj2, obj3];

What are other ways of achieving the same result, maybe using a shorter syntax?


Solution

  • While your code is working fine and is a valid way to achieve this (although I'd suggest using const instead of var), I would suggest potentially performing a mapping (this can be useful if you have more than one object in your original array, perhaps then you can consider using .map() instead of .flatMap()):

    const res = {data: [ {name: 'c2', ipaddr: '192.168.1.5', port: 4435, sshuser: "abc", sshpass: "xyz", sshport: 22, license: 'license.txt'}]};
    
    const newState = res.data.flatMap(({name, ipaddr, port, sshuser, sshpass, sshport, license}) => [
      {name, ipaddr, port}, {sshuser, sshpass, sshport}, {license}
    ]);
    
    console.log(newState);

    Alternatively, you can destructure your objects from your array, and create the array of objects using shorthand property names:

    const res = {data: [ {name: 'c2', ipaddr: '192.168.1.5', port: 4435, sshuser: "abc", sshpass: "xyz", sshport: 22, license: 'license.txt'}]};
    
    const [{name, ipaddr, port, sshuser, sshpass, sshport, license}] = res.data;
    const newState = [{name, ipaddr, port}, {sshuser, sshpass, sshport}, {license}];
    console.log(newState);