如何在JavaScript中将嵌套对象转换为键值对

发布于 2025-02-12 05:49:26 字数 313 浏览 0 评论 0 原文

我想通过编程

问题

  attributes: {
    allow: [ '0' ],
    create: [ '0' ],
    all: [ '0' ],
    rfid: [ '0' ],
}

我想要的是

  attributes: {
    allow:'0',
    create: '0',
    all:'0',
    rfid: '0',
}

I want to do this with programming

Problem

  attributes: {
    allow: [ '0' ],
    create: [ '0' ],
    all: [ '0' ],
    rfid: [ '0' ],
}

What I want is

  attributes: {
    allow:'0',
    create: '0',
    all:'0',
    rfid: '0',
}

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

╭ゆ眷念 2025-02-19 05:49:26

功能方法:

您可以使用 object.entries 转动对象 {a:1, B:2} 进入数组数组(包含键和值对) [['a',1],['b',2]] 。然后,您可以使用 在每个操作上应用一个操作,并将数组的每个元素映射到操作的返回值。在我们的情况下,实际上我们将拥有 [['lever',['0']],...] 之类的东西,并希望将其映射到 [['['['['['允许','0'],... 。然后,在最后,我们使用 object.fromentries 取回对象。

映射操作可以简单地([K,[V]])=> [k,v] 。使用破坏性,我们获得了一种表达方式来提取所需的价值并返回它。

现在,由于整个过程似乎都在另一个具有属性为键的对象内部(而且我不知道是否可以使用其他键),所以我们将带有属性的另一个此类对象< /code>更换并保留了其他键:

function transform (object) {
  return {
    ...object,
    attributes: Object.fromEntries(
      Object.entries(object.attributes).map(([k, [v]]) => [k, v])
    )
  }
}

命令方法:

此方法更简单,但会突变您的对象。您可以在属性对象中的键上循环,并用自己的第一个数组元素替换每个值,如下所示:

function transform (object) {
  for (const key in object.attributes) {
    object.attributes[key] = object.attributes[key][0]
  }
  
  return object
}

Functional approach:

You can use Object.entries to turn an object { a: 1, b: 2 } into an array of arrays (containing pairs of keys and values) [['a', 1], ['b', 2]]. You can then use Array#map to apply an operation on each and mapping each element of the array to the return value of the operation. In our case, we'll actually have something like [['allow', ['0']], ...] at that point and want to map it to [['allow', '0'], ...]. Then at the end, we undo the first operation using Object.fromEntries to get an object back.

The mapping operation can be simply ([k, [v]]) => [k, v]. Using destructuring, we get an expressive way of extracting the value that we need and returning it.

Now since the whole thing seems to be inside another object with attributes as key (and I don't know if there can be other keys), we'll return another such object with attributes replaced and the other keys preserved:

function transform (object) {
  return {
    ...object,
    attributes: Object.fromEntries(
      Object.entries(object.attributes).map(([k, [v]]) => [k, v])
    )
  }
}

Imperative approach:

This approach is simpler, but will mutate your object. You can loop over the keys in the attributes object and replace each value with its own first array element, as follows:

function transform (object) {
  for (const key in object.attributes) {
    object.attributes[key] = object.attributes[key][0]
  }
  
  return object
}
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文