我在將一組物件轉換為我的作業的物件物件時遇到了問題。公司 API 需要這種格式的資料。任何幫助,將不勝感激。這是一個例子
原來的
const array = [
{
type: 'ITEM',
info: {
item_id: 'house'
}
},
{
type: 'ITEM',
info: {
item_id: 'house'
}
}
]
最后
const array = {
{
type: 'ITEM',
info: {
item_id: 'house'
}
},
{
type: 'ITEM',
info: {
item_id: 'house'
}
}
}
uj5u.com熱心網友回復:
您必須對物件元素使用鍵/值對,但您可以從該陣列創建一個物件,如下所示:
const array = [
{
type: 'ITEM',
info: {
item_id: 'house'
}
},
{
type: 'ITEM',
info: {
item_id: 'house'
}
}
]
let result = {}
array.forEach((el, idx) => {
result['data_' idx] = el
})
console.log(result)
uj5u.com熱心網友回復:
您的物件將需要密鑰。Javascript 中的物件始終是 { key:value, ...} (鍵值對)。
因此,您需要創建這些:
const array = [
{
type: 'ITEM',
info: {
item_id: 'house'
}
},
{
type: 'ITEM',
info: {
item_id: 'house'
}
}
]
const obj = array.reduce((o,e,i) => { return { ...o, ['item_' i]: e }}, {});
console.log(obj);
將“items_”更改為適合您目的的任何內容。如果可能的話,我建議在這里使用一個陣列。
轉載請註明出處,本文鏈接:https://www.uj5u.com/qukuanlian/390122.html
標籤:javascript 数组 目的
上一篇:輸入特定值時如何過濾輸入值
