简体   繁体   中英

How to structure array of items to create an array of objects

My server expects an object like the following:

{
    "name":"test",
    "detail":[
        {"iddetail":1},
        {"iddetail":2}
    ]
}

In the frontend I have a control that takes multiple details:

<v-autocomplete
   v-model="items">
</v-autocomplete>

As my server expects:

 "detail":[
        {"iddetail":1},
        {"iddetail":2}
    ]

But my frontend returns:

items = [1,2]

I do the following:

data.items.map(function(x){
   data.detail.push({iddetail:x})
});

That works, but the question is whether it can be done in a simpler and more efficient way.

const items = [1,2];
const data = {
   name: '...',
   detail: items.map( i => ({iddetail:i}) )
};

And of course, it's always more convenient to have similar format between api and front code but small conversion is good enough

不确定,但也许这个

data.detail = items.map((x) => ({iddetail:x}));

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM