Quentin Del
Quentin Del

Reputation: 1685

Destructure Array and assign to property object in one line

I have these Javascript lines :

const record = {};
const parts = ['deviceId-abc', 'messagesId-def'];

record.deviceId = parts[0];
record.messageId = parts[1];

I have a linter error prefer-destructuring on the last two lines but I am not sure how I can both destructure an array and assign the value to an object property.

thanks,

Upvotes: 2

Views: 723

Answers (5)

Y4glory
Y4glory

Reputation: 1146

You can destructure the array-like this

const record = {};
const parts = ['deviceId-abc', 'messagesId-def'];

[record.deviceId,record.messageId]=parts;

console.log(record);

Upvotes: 0

Patrick Roberts
Patrick Roberts

Reputation: 51816

I'd personally do this:

const [deviceId, messageId] = ['deviceId-abc', 'messagesId-def'];
const record = { deviceId, messageId };

Upvotes: 1

Kesav
Kesav

Reputation: 149

Try something like this

const record = {};
const [parts,message]=['deviceId-abc', 'messagesId-def'];

record.deviceId = parts
record.messageId = message

Upvotes: 0

Nina Scholz
Nina Scholz

Reputation: 386550

You could destructure an array and take the properties as target.

const
    record = {},
    parts = ['deviceId-abc', 'messagesId-def'];

[record.deviceId, record.messageId] = parts;

console.log(record);

Upvotes: 2

7hibault
7hibault

Reputation: 2459

You can destructure into your properties

const record = {};
const parts = ['deviceId-abc', 'messagesId-def'];

[record.deviceId, record.messageId] = parts;

Upvotes: 4

Related Questions