I am trying to return multiple objects without their index, however, I cannot find a way using Objects. This is what I have tried so far, am I missing something?
const fields = [
'name',
'age',
'address'
];
const builtFields = []
for (let i = 0; i < fields.length; i++) {
builtFields.push(
{
[fields[i]]: { type: '' }
}
)
}
fields: Object.assign({}, builtFields)
console.log(fields)
Outputs:
fields: {
0: { name: { type: '' } },
1: { age: { type: '' } },
2: { address: { type: '' } }
}
Desired output:
fields: {
name: { type: '' },
age: { type: '' },
address: { type: '' }
}
You're currently assigning the array entries to the object while you actually want to add each array item (which is an entry) to the empty object:
fields: Object.assign({}, ...builtFields)
As a shortest solution:
const fields = [
'name',
'age',
'address'
];
const obj = Object.fromEntries(fields.map(x => [x, { type: '' }]));
console.log(obj);