2 回答

TA貢獻(xiàn)1821條經(jīng)驗(yàn) 獲得超5個(gè)贊
簡(jiǎn)單的 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);

TA貢獻(xiàn)1820條經(jīng)驗(yàn) 獲得超10個(gè)贊
你可以使用 Lodash's _.mergeWith()with array spread 將數(shù)組中的所有項(xiàng)目組合成一個(gè)對(duì)象。如果兩個(gè)對(duì)象中存在相同的屬性,則這些值將被收集到一個(gè)數(shù)組中:
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,您可以fn使用 生成一個(gè)函數(shù) ( ) _.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>
添加回答
舉報(bào)