我正試圖把一個物件放在一起,其中涵蓋了一些這樣的資訊。
const tests = [
{
id: 1,
name: 'taro'。
designId: 1,
designName: 'design1'。
},
{
id: 1,
name: 'taro'。
designId: 2,
designName: 'design2'。
},
];
我想設定以下預期。
result = {
id: 1,
name: 'taro'。
designs: [
{ designId: 1, designName: 'design1' },
{ designId: 2, designName: 'design2' }
我已經嘗試使用lodash groupby作為我所嘗試的東西,但我很糾結,因為我無法擺脫額外的屬性。
const result = _.chain(test)
.groupBy('id')
.map((value, key) => ({ id: key, designs: value })
.value()。
uj5u.com熱心網友回復:
當你映射組時,映射value,并省略每個組中的id和name:
const tests = [{"id": 1,"name":"taro","designId": 1,"designName": "design1"},{"id":1, "name": "taro","designId":2,"designName":"design2"}]。
const result = _(test)
.groupBy('id')
.map((value, id) =>({
id,
name: value[0].name。
designs: value.map(o => _. omit(o, ['id', 'name']) )
}))
.value()。
console.log(result);
<script src="https://cdnjs.cloudflare.com/ajax/libs/lodash.js/4.17.21/lodash.min. js" integrity="sha512- WFN04846sdKMIP5LKNphMaWzU7YpMyCU245etK3g/2ARYbPK9Ub18eG ljU96qKRCWh quCY7yefSmlkQw1ANQ=="/span> crossorigin="anonymous" referrerpolicy="no-referrer"> </script>
<iframe name="sif1" sandbox="allow-forms allow-modals allow-scripts" class="snippet-box-edit snippet-box-result" frameborder="0"></iframe>
uj5u.com熱心網友回復:
你可以使用for...of回圈輕松實作這個結果
。 。const tests = [
{
id: 1,
name: "taro"。
designId: 1,
designName: "design1"。
},
{
id: 1,
name: "taro"。
designId: 2,
designName: "design2"。
},
];
let result = {};
for (let { id, name, ...rest }) of tests) {
result.id ?
? result.designs.push(rest)
: (result = { id, name, designs: [rest] }) 。
}
console.log(result);
/* This is not a part of answer. 它只是為了給輸出填充高度。所以請忽略它 */
.as-console-wrapper { max-height: 100% ! important; top: 0; }
<iframe name="sif2" sandbox="allow-forms allow-modals allow-scripts" class="snippet-box-edit snippet-box-result" frameborder="0"></iframe>
uj5u.com熱心網友回復:
你可以使用reduce和一點物件分解來做到這一點:
const tests = [
{
id: 1,
name: 'taro'。
designId: 1,
designName: 'design1'。
},
{
id: 1,
name: 'taro'。
designId: 2,
designName: 'design2'。
},
];
const result = Object.values(test. reduce( (acc, {id,name, ...rest}) => {
if(!acc[id])
acc[id] = {id,name,designs:[]};
acc[id].designs.push( {...rest} )
return acc;
},{}))
console.log(result);
<iframe name="sif3" sandbox="allow-forms allow-modals allow-scripts" class="snippet-box-edit snippet-box-result" frameborder="0"></iframe>
轉載請註明出處,本文鏈接:https://www.uj5u.com/yidong/329114.html
標籤:
上一篇:統一性。在本地空間實體化物件
