I am having trouble converting an array of objects into an object of objects for my job. The company API is expecting the data in this format. Any help would be appreciated. Here is an example
Original
const array = [
{
type: 'ITEM',
info: {
item_id: 'house'
}
},
{
type: 'ITEM',
info: {
item_id: 'house'
}
}
]
Final
const array = {
{
type: 'ITEM',
info: {
item_id: 'house'
}
},
{
type: 'ITEM',
info: {
item_id: 'house'
}
}
}
CodePudding user response:
You have to use key/value pairs for object elements, but you can create an object from this array like this:
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)
CodePudding user response:
Your Object will need keys. An Object in Javascript is always { key:value, ...} (key-value pairs).
Therefor you will need to create these:
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);
change 'items_' to whatever suits your purpose. If possible I'd suggest using an array here though.