第七色在线视频,2021少妇久久久久久久久久,亚洲欧洲精品成人久久av18,亚洲国产精品特色大片观看完整版,孙宇晨将参加特朗普的晚宴

為了賬號(hào)安全,請(qǐng)及時(shí)綁定郵箱和手機(jī)立即綁定
已解決430363個(gè)問(wèn)題,去搜搜看,總會(huì)有你想問(wèn)的

如何將多個(gè)對(duì)象的數(shù)組合并為單個(gè)對(duì)象?

如何將多個(gè)對(duì)象的數(shù)組合并為單個(gè)對(duì)象?

所以,我有一個(gè)這樣的數(shù)組:[  { tags__region: "Stockholm" },  { tags__region: "Lund" },  { tags__region: "Mora" },  { tags__user: "Johan" },  { tags__user: "Eva" }]我想把它變成這樣的對(duì)象:{  tags__region: ["Stockholm", "Lund", "Mora"],   tags__user: ["Johan", "Eva"]}有沒(méi)有辦法用lodash?vanilla Array/Object - 方法是否足夠簡(jiǎn)單?請(qǐng)記住,我陣列上的鍵是未知的,因此它們并不總是相同的。
查看完整描述

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);


查看完整回答
反對(duì) 回復(fù) 2022-07-08
?
拉莫斯之舞

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>



查看完整回答
反對(duì) 回復(fù) 2022-07-08
  • 2 回答
  • 0 關(guān)注
  • 165 瀏覽
慕課專欄
更多

添加回答

舉報(bào)

0/150
提交
取消
微信客服

購(gòu)課補(bǔ)貼
聯(lián)系客服咨詢優(yōu)惠詳情

幫助反饋 APP下載

慕課網(wǎng)APP
您的移動(dòng)學(xué)習(xí)伙伴

公眾號(hào)

掃描二維碼
關(guān)注慕課網(wǎng)微信公眾號(hào)