分解数组并在一行中分配给属性对象

时间:2020-04-07 08:21:00

标签: javascript ecmascript-6 destructuring

我有这些Javascript行:

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

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

我在最后两行有一个linter错误 prefer-destructuring ,但是我不确定如何既可以分解数组,又可以将值分配给对象属性。

谢谢

5 个答案:

答案 0 :(得分:4)

您可以将其分解为属性

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

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

答案 1 :(得分:2)

您可以解构数组并将属性作为目标。

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

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

console.log(record);

答案 2 :(得分:1)

我个人会这样做:

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

答案 3 :(得分:0)

尝试这样的事情

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

record.deviceId = parts
record.messageId = message

答案 4 :(得分:0)

您可以像这样破坏数组

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

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

console.log(record);