我正在制作一個使用sequelize的應用程式,回傳的JSON值是:
[
{ key: 'PREFIX', value: 'm.' },
{ key: 'OWNER_ID', value: '14901414891498' },
{ key: 'GUILD_ID', value: '525219058950109' }
]
但是我想知道是否有可能將這個json物件重新組織成這樣:
{ prefix: 'm.', owner_id: '330406276972412928', guild_id: '525219058950109'}
我搜索了一些用Javascript操作JSON物件的方法,但都不符合我的需要。
uj5u.com熱心網友回復:
使用Array#reduce:
const data = [ { key: 'PREFIX', value: 'm.' }, { key: 'OWNER_ID', value: '14901414891498' }, { key: 'GUILD_ID', value: '525219058950109'/span> } ];
const obj = data.reduce((acc, {key, value}) =>({.
...acc, [key.toLowerCase()] : value
}), {});
console.log(obj);
<iframe name="sif1" sandbox="allow-forms allow-modals allow-scripts" class="snippet-box-edit snippet-box-result" frameborder="0"></iframe>
uj5u.com熱心網友回復:
你可以使用Object.fromEntries并將物件轉換成[key, value]圖元。
const data = [
{ key: 'PREFIX', value: 'm.' },
{ key: 'OWNER_ID', value: '14901414891498' },
{ key: 'GUILD_ID', value: '525219058950109' }
]
const newData = Object.fromEntries(資料。 map(({ key, value }) =>/span>。
[key.toLowerCase(), value])
console.log(newData)
<iframe name="sif2" sandbox="allow-forms allow-modals allow-scripts" class="snippet-box-edit snippet-box-result" frameborder="0"></iframe>
轉載請註明出處,本文鏈接:https://www.uj5u.com/shujuku/321058.html
標籤:
