I need to create multiple objects, and each one must have an ID.
All of them will be inside an Array.
So it will look like this:
const array = [
{
id: 1,
bla: "bla"
},
{
id: 2,
bla: "bla"
},
{
id: 3,
bla: "bla"
}
]
my question is, Is there a way to create a function, the will return a number that i can put inside those id's?
CodePudding user response:
You likely want what we call generators/iterators.
An generator/iterator is a function that has an inner state.
In js, it's created by adding an "*" next to the "function" and using "yield" keyword instead of "return" (see https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/yield).
When the generator is called, it saves the arguments it was given and returns an iterator, on which you can call .next() to get the next value (note an object with "value" attribute is returned).
function* idGenerator (startingIndex) {
while (true){
//the iterator will keep his inner state
startingIndex = 1;
yield startingIndex;
}
}
CodePudding user response:
function makeArrayWithId(...objects) {
return objects.map((o, i) => ({ id: i 1, ...o }))
}
const arr = makeArrayWithId(
{
bla: "bla"
},
{
bla: "bla"
},
{
bla: "bla"
},
)
console.log(arr)
it will prints:
[ { id: 1, bla: 'bla' }, { id: 2, bla: 'bla' }, { id: 3, bla: 'bla' } ]
if you already have an array that each object has no id, you can pass it to this function like this:
let myArr = [
{
bla: 'bla'
},
{
bla: 'bla'
},
{
bla: 'bla'
},
]
myArrr = makeArrayWithId(...myArr)
console.log(myArr)
it will prints:
[ { id: 1, bla: 'bla' }, { id: 2, bla: 'bla' }, { id: 3, bla: 'bla' } ]
CodePudding user response:
let array = [
{
bla: "bla"
},
{
bla: "bla"
},
{
bla: "bla"
}
]
array = array.map((item, index) => Object.assign({}, item, { id: index 1 }))
Output:
[ { bla: 'bla', id: 1 },
{ bla: 'bla', id: 2 },
{ bla: 'bla', id: 3 } ]