【问题标题】:Manipulation JSON with Lodash使用 Lodash 操作 JSON
【发布时间】:2018-09-14 12:50:53
【问题描述】:

使用这个代码let result = _.groupBy(obj, 'type');我有这个回报:

{
    "success": [{
        "type": "success",
        "messages": "Assignment saved."
    }, {
        "type": "success",
        "messages": "Assignment saved."
    }, {
        "type": "success",
        "messages": "Assignment saved."
    }]
}

但我需要转换成这个:

{
    "error": ["Error msg", "Error 2 msg", "Error 3 msg"],
    "notice": ["Notice 1 msg", "Notice 2 msg"],
    "success": ["Success 1 msg", "Success 2 msg", "Success 3 msg"]
}

我应该在我的代码中做些什么不同的事情?

我缺少 Lodash 上的一些配置?

【问题讨论】:

  • 它们是按类型分组的,并不是要修改对象
  • 是的,我需要找到一种方法来做到这一点。我需要groupBy 并额外调整我的return 以获得array。但我找不到任何关于如何使用groupBy 操作objectdocumentation
  • 那么,在输入对象中,您已经有一个名为success 的键,它是一个数组?或者它只是groupBy 的结果?同样,errornotice 有单独的数组吗?或者您在一个数组中拥有的所有数据,并且 .key 数组的名称是 success (这很尴尬)。你能告诉我们原始输入吗?
  • 您应该粘贴原始的obj。此外,期望值显示其他对象中未显示的键和消息,这是没有意义的。

标签: javascript json lodash


【解决方案1】:

查看this fiddle 以获得有效的解决方案。 使用此解决方案,您不会被锁定在相同的 3 类消息中。

我用过_.groupBy

let list = [{type: "success", message: "msg1"},{type: "success", message: "msg2"},{type: "success", message: "msg3"},{type: "notice", message: "msg1"}, {type: "notice", message: "msg2"}, {type: "error", message: "msg1"}]

console.log("\n\n---------Full initial list of events");
console.log(list);

console.log("\n\n---------Events grouped by type");
console.log(_.groupBy(list, 'type'));

console.log("\n\n---------Your format");
let groups = _.groupBy(list, 'type')
let keys = Object.keys(groups);
for (let key of keys) {
    groups[key] = groups[key].map(elem => elem.message)
}
console.log(groups);

【讨论】:

  • 你冷也行_.forOwn(groups, v => v.map((v2,i,a) => a[i] = v2.message))
【解决方案2】:

问题中包含的代码令人困惑。像这样?

const result = _(obj)
  .groupBy("type")
  .mapValues(objs => objs.map(o => o.messages))
  .value()

【讨论】:

  • @CoderPi: 1) lodash 是否加载到这个小提琴中?,2) OP 有 messages 作为键,而不是 message
【解决方案3】:

图书馆并不总是可行的方法:

function groupMessagesByType(dataIn) {
  let dataOut = {}
  
  for(var i = 0; i < dataIn.length; ++i) {
    var type = dataIn[i].type
    if(typeof dataOut[type] == "undefined") {
      dataOut[type] = []
    }
    dataOut[type].push(dataIn[i].messages)
  }

  return dataOut
}

// Example:
var data = [{
        "type": "success",
        "messages": "Assignment saved."
    }, {
        "type": "success",
        "messages": "Assignment saved."
    }, {
        "type": "error",
        "messages": "Error msg."
    }]
console.log(groupMessagesByType(data))

【讨论】:

  • 谢谢,这个解决方案有效。我也做过类似的事情,但在这种情况下我试图使用 LoDash 但这是不可能的,或者我错过了一些信息。再次感谢,伙计。
  • 你可以在没有库的情况下做任何事情,但如果使用它们使代码更具声明性(并且可能更短),使用众所周知的功能抽象(map、filter、sortBy 等),为什么不呢?
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2016-04-01
  • 1970-01-01
  • 2023-03-26
  • 1970-01-01
  • 2021-12-17
  • 2019-03-14
相关资源
最近更新 更多