【问题标题】:Properties of object into a comma separated string [closed]对象的属性转换为逗号分隔的字符串 [关闭]
【发布时间】:2021-02-17 09:11:33
【问题描述】:

我有一个解决方案,我迭代每个对象键及其值,但它对我来说似乎有点“hacky”。是否有人使用 ES6Object.values 或其他方法有更好的解决方案?

原始对象

metrics = {
  "credit": {
    "sum": false,
    "mean": false,
    "max": true,
    "min": true,
  },
  "debit": {
    "sum": false,
    "mean": true,
    "max": true,
    "min": false,
  },
  ...
}

假装字符串

credit:max,credit:min,debit:mean,debit:max

当前解决方案

let string = []

Object.keys(metrics).forEach(column => {
  Object.keys(metrics[column]).forEach(metric => {
    if (metrics[column][metric]) { 
      string.push(`${column}:${metric}`)
    }
  })
})


string = string.join(',')

谢谢。

【问题讨论】:

  • 您有什么解决方案?为什么你认为它是“hacky”? “转换后的”字符串是如何确定的? 究竟你想做什么?
  • 我已经更新了这个问题。我遍历每个对象并将其推送到稍后加入的新数组。提前感谢@RocketHazmat。
  • 你有什么问题?你的代码给出了正确的答案吗?你能分享你的代码吗?
  • @RocketHazmat 我在问题中分享了我的代码。
  • 你的代码有什么问题?它对我来说看起来不错,并为您提供正确的输出。我想你可以用.filter()/.map() 做点什么,但我不知道它是否会更“干净”。

标签: javascript arrays object ecmascript-6 filter


【解决方案1】:

使用Object.entries 需要知道 并提供要处理的参考...这里metrics ...恰好一次。因此,所有剩余代码的实现不需要对这个引用的名称做出假设,而只是关于这个数据引用的结构以及如何reduce它...

const metrics = {
  "credit": {
    "sum": false,
    "mean": false,
    "max": true,
    "min": true,
  },
  "debit": {
    "sum": false,
    "mean": true,
    "max": true,
    "min": false,
  },
};

console.log(
  Object
    .entries(metrics)
    .reduce((list, [key, obj]) => [

      ...list,
      ...Object
        .entries(obj)
        .reduce((list, [value, bool]) =>

          (bool && [...list, `${ key }:${ value }`]) || list,
          []
        )
    ], []).join(',')
);
.as-console-wrapper { min-height: 100%!important; top: 0; }

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2023-04-09
    • 2019-01-23
    • 1970-01-01
    • 1970-01-01
    • 2014-12-31
    • 1970-01-01
    • 2021-08-09
    相关资源
    最近更新 更多