英文:
convert JS object to Object Array
问题
I have an array of objects as below:
[
{
Instance: 'USM 1',
performance: '<DanPac_A>.<Daniel.DanOPCHub>.<A Session.Perfomance>',
agc: '<DanPac_A>.<Daniel.DanOPCHub>.<A Session.AGC>',
snr: '<DanPac_A>.<Daniel.DanOPCHub>.<A Session.SNR>',
sos: '<DanPac_A>.<Daniel.DanOPCHub>.<A Session.SNR>',
flowvel: '<DanPac_A>.<Daniel.DanOPCHub>.<A Session.SNR>',
},
];
I need to take Instance
out as a key and use its value as a property instead.
Expected output:
[
{
'USM 1': [
{
performance: 'value',
agc: 'value',
// ...
},
],
},
];
Any idea how to take it out?
英文:
I have an array of objects as below
[
{
Instance: 'USM 1',
performance:
'&lt;DanPac_A&gt;.&lt;Daniel.DanOPCHub&gt;.&lt;A Session.Perfomance&gt;',
agc: '&lt;DanPac_A&gt;.&lt;Daniel.DanOPCHub&gt;.&lt;A Session.AGC&gt;',
snr: '&lt;DanPac_A&gt;.&lt;Daniel.DanOPCHub&gt;.&lt;A Session.SNR&gt;',
sos: '&lt;DanPac_A&gt;.&lt;Daniel.DanOPCHub&gt;.&lt;A Session.SNR&gt;',
flowvel: '&lt;DanPac_A&gt;.&lt;Daniel.DanOPCHub&gt;.&lt;A Session.SNR&gt;',
},
];
I need to take Instance
out as a key and use its value as a property instead.
expected output
[
{
'USM 1': [
{
performance: 'value',
agc: 'value',
// ...
},
],
},
];
any idea how to take it out??
答案1
得分: 0
你可以使用 Array::map()
方法:
const arr = [{
"Instance": "USM 1",
"performance": "<DanPac_A>.<Daniel.DanOPCHub>.<A Session.Perfomance>",
"agc": "<DanPac_A>.<Daniel.DanOPCHub>.<A Session.AGC>",
"snr": "<DanPac_A>.<Daniel.DanOPCHub>.<A Session.SNR>",
"sos": "<DanPac_A>.<Daniel.DanOPCHub>.<A Session.SNR>",
"flowvel": "<DanPac_A>.<Daniel.DanOPCHub>.<A Session.SNR>"
}];
const mapped = arr.map(({Instance, ...item}) => ({[Instance]: [item]}));
console.log(mapped);
英文:
You could use Array::map()
:
<!-- begin snippet: js hide: false console: true babel: false -->
<!-- language: lang-js -->
const arr = [{
"Instance": "USM 1",
"performance": "&lt;DanPac_A&gt;.&lt;Daniel.DanOPCHub&gt;.&lt;A Session.Perfomance&gt;",
"agc": "&lt;DanPac_A&gt;.&lt;Daniel.DanOPCHub&gt;.&lt;A Session.AGC&gt;",
"snr": "&lt;DanPac_A&gt;.&lt;Daniel.DanOPCHub&gt;.&lt;A Session.SNR&gt;",
"sos": "&lt;DanPac_A&gt;.&lt;Daniel.DanOPCHub&gt;.&lt;A Session.SNR&gt;",
"flowvel": "&lt;DanPac_A&gt;.&lt;Daniel.DanOPCHub&gt;.&lt;A Session.SNR&gt;"
}];
const mapped = arr.map(({Instance, ...item}) => ({[Instance]: [item]}));
console.log(mapped);
<!-- end snippet -->
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论