使用 lodash 的紧凑对象数组

我有一个对象数组,比如第一个 json。


基于属性名称,我想将这个数组压缩到另一个中,就像那样。如果名称与另一个对象相同,则编译该对象并将其他属性和值设置为字段数组。


   { 

      "name":"D1D1",

      "attritube":"HOST_NAME",

      "value_inv":"TEST1",

      "value_prod":"TESTA1"

   },

   { 

      "name":"D1D1",

      "attritube":"HOST_NAME",

      "value_inv":"TEST2",

      "value_prod":"TESTB1"

   },

   { 

      "name":"D2D2",

      "attritube":"COMMENTS",

      "value_inv":"TEST1",

      "value_prod":"TESTA1"

   }

]





   { 

      "name":"D1D1",

      "fields":[ 

         { 

            "attritube":"HOST_NAME",

            "value_inv":"TEST1",

            "value_prod":"TESTA1"

         },

         { 

            "attritube":"HOST_NAME",

            "value_inv":"TEST2",

            "value_prod":"TESTB1"

         }

      ]

   },

   { 

      "name":"D2D2",

      "fields":[ 

         { 

            "attritube":"COMMENTS",

            "value_inv":"TEST1",

            "value_prod":"TESTA1"

         }

      ]

   }

]


慕丝7291255
浏览 110回答 1
1回答

慕哥9229398

这并不漂亮,当您拥有非常大的数据集时,它的性能也不会很好,但它可以正常工作并产生您期望的输出。const arr = [&nbsp;&nbsp; &nbsp;{&nbsp;&nbsp; &nbsp; &nbsp; "name":"D1D1",&nbsp; &nbsp; &nbsp; "attritube":"HOST_NAME",&nbsp; &nbsp; &nbsp; "value_inv":"TEST1",&nbsp; &nbsp; &nbsp; "value_prod":"TESTA1"&nbsp; &nbsp;},&nbsp; &nbsp;{&nbsp;&nbsp; &nbsp; &nbsp; "name":"D1D1",&nbsp; &nbsp; &nbsp; "attritube":"HOST_NAME",&nbsp; &nbsp; &nbsp; "value_inv":"TEST2",&nbsp; &nbsp; &nbsp; "value_prod":"TESTB1"&nbsp; &nbsp;},&nbsp; &nbsp;{&nbsp;&nbsp; &nbsp; &nbsp; "name":"D2D2",&nbsp; &nbsp; &nbsp; "attritube":"COMMENTS",&nbsp; &nbsp; &nbsp; "value_inv":"TEST1",&nbsp; &nbsp; &nbsp; "value_prod":"TESTA1"&nbsp; &nbsp;}];const newArr = _.chain(arr)&nbsp; .groupBy('name')&nbsp; .toPairs()&nbsp; .map((val) => ({&nbsp; &nbsp; name: val[0],&nbsp; &nbsp; fields: _.map(val[1], (v) => _.omit(v, ['name']))&nbsp; }))&nbsp; .value();&nbsp;&nbsp;console.log(newArr);<script src="https://cdnjs.cloudflare.com/ajax/libs/lodash.js/4.17.15/lodash.min.js"></script>
打开App,查看更多内容
随时随地看视频慕课网APP

相关分类

JavaScript