如何将多个对象的数组合并为单个对象?

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


[

  { 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 - 方法是否足够简单?


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



拉风的咖菲猫
浏览 183回答 2
2回答

收到一只叮咚

简单的 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);

拉莫斯之舞

你可以使用 Lodash's _.mergeWith()with array spread 将数组中的所有项目组合成一个对象。如果两个对象中存在相同的属性,则这些值将被收集到一个数组中:const arr = [{"tags__region":"Stockholm"},{"tags__region":"Lund"},{"tags__region":"Mora"},{"tags__user":"Johan"},{"tags__user":"Eva"}]const result = _.mergeWith({}, ...arr, (objValue = [], srcValue) =>&nbsp;&nbsp; [...objValue, srcValue])console.log(result)<script src="https://cdnjs.cloudflare.com/ajax/libs/lodash.js/4.17.15/lodash.js"></script>使用 Lodash/fp,您可以fn使用 生成一个函数 ( ) _.mergeAllWith(),_.concat()这将做同样的事情: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>
打开App,查看更多内容
随时随地看视频慕课网APP

相关分类

JavaScript