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?
While your code is working fine and is a valid way to achieve this (although I'd suggest using
constinstead ofvar), 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()):Alternatively, you can destructure your objects from your array, and create the array of objects using shorthand property names: