【问题标题】:How to consolidate an array of multiple objects into single object?如何将多个对象的数组合并为单个对象?
【发布时间】:2020-04-21 08:38:41
【问题描述】:

所以,我有一个这样的数组:

[
  { tags__region: "Stockholm" },
  { tags__region: "Lund" },
  { tags__region: "Mora" },
  { tags__user: "Johan" },
  { tags__user: "Eva" }
]

我想把它变成这样的对象:

{
  tags__region: ["Stockholm", "Lund", "Mora"], 
  tags__user: ["Johan", "Eva"]
}

lodash 有什么办法吗? vanilla Array/Object 方法足够简单吗?

请记住,我的阵列上的键是未知的,因此它们并不总是相同的。

【问题讨论】:

    标签: javascript arrays lodash


    【解决方案1】:

    简单的 Javascript。

    let arr = [{
        tags__region: "Stockholm"
      },
      {
        tags__region: "Lund"
      },
      {
        tags__region: "Mora"
      },
      {
        tags__user: "Johan"
      },
      {
        tags__user: "Eva"
      }
    ];
    
    arr = arr.reduce((acc, val) => {
    
      let key = Object.keys(val)[0];
      let value = Object.values(val)[0];
      acc[key] =  acc[key] ? [...acc[key],value] : [value]
      return acc;
    }, {})
    
    console.log(arr);

    【讨论】:

    • 非常感谢!美丽的! (不幸的是,我在这里太新了,无法回答您)
    【解决方案2】:

    您可以使用 Lodash 的 _.mergeWith() 和数组展开将数组中的所有项目组合成一个对象。如果两个对象中存在相同的属性,则将值收集到一个数组中:

    const arr = [{"tags__region":"Stockholm"},{"tags__region":"Lund"},{"tags__region":"Mora"},{"tags__user":"Johan"},{"tags__user":"Eva"}]
    
    const result = _.mergeWith({}, ...arr, (objValue = [], srcValue) => 
      [...objValue, srcValue]
    )
    
    console.log(result)
    <script src="https://cdnjs.cloudflare.com/ajax/libs/lodash.js/4.17.15/lodash.js"></script>

    使用 Lodash/fp,您可以使用 _.mergeAllWith()_.concat() 生成一个函数 (fn),它会做同样的事情:

    const fn = _.mergeAllWith(_.concat)
    
    const arr = [{"tags__region":"Stockholm"},{"tags__region":"Lund"},{"tags__region":"Mora"},{"tags__user":"Johan"},{"tags__user":"Eva"}]
    
    const result = fn(arr)
    
    console.log(result)
    <script src='https://cdn.jsdelivr.net/g/lodash@4(lodash.min.js+lodash.fp.min.js)'></script>

    【讨论】:

    • 谢谢你也很整洁
    猜你喜欢
    • 2022-11-08
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2015-12-21
    • 2018-02-09
    • 1970-01-01
    相关资源
    最近更新 更多