Reputation: 395
Trying to add an ID to each object in an array. And if the id already exists the id will increment by 1, trying to get an auto increment function going. The problem is that with this function every object either gets the same ID when running the for loop inside the for each statement or I get cannot read obj.id of undefined
if the loop runs outside.
function addId(arr, obj) {
obj.id;
arr.forEach(function(obj) {
obj.id = 0;
return obj.id;
});
for(var i = 0; i <= arr.length; i++) {
if(obj.id == obj.id) obj.id++;
}
};
Upvotes: 1
Views: 3123
Reputation: 21
Here is the updated version with arrow functions and spread
const addId=(arr)=> {
return arr.map((obj, index)=> {
return ({...obj,id: index })
});
};
// test
const input = [ { a: 1 }, { a: 2 }, { a: 3 }, { a: 4 }];
addId(input)
console.log(addId(input))
Or Even cleaner
const addId=(arr)=> arr.map((obj, index)=>({...obj,id: index }));
// test
const input = [ { a: 1 }, { a: 2 }, { a: 3 }, { a: 4 }];
addId(input)
console.log(addId(input))
Upvotes: 1
Reputation: 14257
There are a few problems with your code. First of all obj.id;
doesn't do anything. So you should get rid of it. Also inside you forEach
you're assigning the value 0
as an id to each object, but in you second loop you're checking if the id of the obj
which is passed in as an argument is the same as itself, therefore the check will always yield true
and then you're incrementing the id of the passed in obj
.
So you're never manipulating the objects inside your array after setting their id attribute to 0
.
You could use the index as the value for the id.
Also if needed you could consider to use something like Object.assign
to prevent altering the original objects inside your array.
function addId(arr) {
return arr.map(function(obj, index) {
return Object.assign({}, obj, { id: index });
});
};
// test
const input = [ { a: 1 }, { a: 2 }, { a: 3 }, { a: 4 }];
const output = addId(input);
console.log(output);
Upvotes: 5