【问题标题】:Destruct a string from split to named object将字符串从拆分破坏为命名对象
【发布时间】:2020-01-06 01:43:36
【问题描述】:

我正在研究如何使用 destruct 一次性创建命名对象

搜索javascript destruct* split object 并没有揭示如何使用拆分直接将字符串解构为对象。

我的意思不是 reduce 或 map,而是纯粹的破坏

const list = { ..... } = `......`.split(..)

至少

const rowItem = { ..... } = `......`.split(..)

我的初始版本有效,但应该有一个更简洁的方法,步骤更少

线的初始分割很好。我很好奇的是使用 destruct 填充列表

const rows = `100|Description 1|a|
101|Description 2|a|
102|Description 3|b|`.split("\n")

let list = {}
rows.forEach(row => {
  const [ProductId, Description, subCat, ] = row.split("|")
  list[ProductId] = {"Description": Description, "subCat": subCat }
})

console.log(list)

【问题讨论】:

  • 你期望从split返回的数组解构成一个对象做什么?
  • 您可以将shorthand property names 用于Description 和subCat
  • 您可以使用Object.fromEntries 使列表的构造更清晰,但我认为这不是您要寻找的内容
  • @JonasHøgh 我不想先 desctruct 创建两个对象,然后解析为第三个对象。
  • @adiga 我可以在 destruct 的同一行中使用它们吗?

标签: javascript ecmascript-6 ecmascript-2016


【解决方案1】:

你可以用 IIFE 做这样的事情

const rows = `100|Description 1|a|
101|Description 2|a|
102|Description 3|b|`.split("\n")

let list = {}
rows.forEach(row => {
  (([ProductId, Description, subCat]) => (list[ProductId] = {
    Description,
    subCat
  }))(row.split("|"))
})

console.log(list)

【讨论】:

  • @mplungjan 我以为你想把所有东西都放在同一行,所以我建议这样做
  • 同一个语句(“一次性”):) 我喜欢将拆分作为参数传递
  • @mplungjan 是的,“一口气”这就是让我想到方法的原因:)
  • 我们可以保存一对括号:) rows.forEach(row => { ( ([ProductId, Description, subCat]) => list[ProductId] = { Description, subCat } )(row.split("|")) })
  • 我现在最喜欢你的。你添加的解构是([ProductId, Description, subCat]),我现在记得我见过
【解决方案2】:

如果您的环境中可用,您可以考虑使用Object.fromEntries

const rows = Object.fromEntries(`100|Description 1|a|
101|Description 2|a|
102|Description 3|b|`
  .split("\n")
  .map(row => row.split('|'))
  .map(([key, Description, subCat]) => [key, { Description, subCat }])
);

console.log(rows);

【讨论】:

  • 嗯,最后一张.map很有意思
  • 不需要.map 后跟.map - 只需在第一个回调中使用拆分字符串并返回数组
  • @CertainPerformance 请显示您的意思的语法?
  • @mplungjan .map(row => { const [key, Description, subCat] = row.split('|'); return [key, { Description, subCat }]; }),看起来和你最初做的很相似
  • @CertainPerformance 是的,这是真的——我喜欢这里的是[key, { Description, subCat }]
【解决方案3】:

可以在解构时将属性设置为现有对象。

const row = { Description: 'Description 1', subCat: 'a' },
      o = { }; // existing object to be updated;

({ Description: o.Description, subCat: o.subCat } = row);

console.log(o)

在您的情况下,您有动态的id 键、嵌套的属性更新,并且您正在解构数组而不是对象。它变得复杂,但是是可以将上述逻辑应用到您的代码(这是非常hackish和纯粹的学术。这应该永远不要用于实际代码库)

const str = "100|Description 1|a|",
      splits = str.split('|'),
      list = {};// existing object
      
({ 0: id, [-1]: list[id]= {}, 1: list[id].Description, 2: list[id].subCat } = splits)

console.log(list)

这会像对象一样解构数组。它使用键0 获取属性并将其设置为id 变量。然后解构-1 属性。这是不存在的,因此使用了default value 并设置了list[id] = {}。

转译后的代码如下所示:

var _str$split = str.split('|');

id = _str$split[0];
list[id] = _str$split[-1] === undefined ? {} : _str$split[-1];
list[id].Description = _str$split[1];
list[id].subCat = _str$split[2];
console.log(list);

将此应用于您的原始 sn-p:

const rows = `100|Description 1|a|
101|Description 2|a|
102|Description 3|b|`

let list = {},
    id;

rows.split("\n")
  .forEach(str => ({
    0: id,
    [-1]: list[id] = {}, 
    1: list[id].Description,
    2: list[id].subCat
  } = str.split('|'))
)

console.log(list)

另一种选择是使用matchAll 和Object.fromEntries()

const str = `100|Description 1|a|
101|Description 2|a|
102|Description 3|b|`;

const regex = /(\d+)\|([^|]+)\|(\w+)/g;
    
const output = Object.fromEntries(
    Array.from(
      str.matchAll(regex), ([, id, Description, subCat]) => [id, { Description, subCat }]
    )
)

console.log(output)

matchAll 仍在Draft stage 中,但除 IE 和 Safari 外,它都已实现。您可以轻松polyfill it。它基本上是循环通过exec结果

【讨论】:

  • 如何改用Array.from的回调,即Array.from(str.matchAll(regex),(([, id, Description, subCat]) => [id, { Description, subCat }])) )
  • 现在更整洁 :) 谢谢
  • @mplungjan 我已经更新了答案。 是可以在同一行中做到这一点。但是,由于嵌套的属性分配,它完全不可读
  • 我不得不承认我真的很喜欢第一个。这是对副作用的讨厌使用,但在格式化时仍然有意义 - 它实际上回答了我提出的问题,但我害怕在现实生活中使用它;)
  • @-1 用于创建以新创建的id 为键的嵌套对象。由于-1 不存在,将使用default value
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2021-03-20
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多