I am not sure if this is a bug from my application, but I have an array like this:
var arr = [{name: 'John'}, {name: 'Jane'}, {name: 'Smith'}, {name: 'George'}];
I am trying to replace {name: 'Jane'} with {name: 'Simon'} so, I am doing
arr.splice(1, 0, {name:'Simon'})
But Jane isn't removed. Just Simon is added to the list.
I thought the splice's first arg was where to place the new array, and 0 was to replace the existing array
var arr = [{
name: 'John'
}, {
name: 'Jane'
}, {
name: 'Smith'
}, {
name: 'George'
}];
arr.splice(1, 0, {
name: 'Simon'
})
console.log(arr)
3 Answers 3
Array#splice is the wrong tool, because it deletes and/or inserts elements.
You could use the index directly and replace the item.
var array = [{ name: 'John' }, { name: 'Jane' }, { name: 'Smith' }, { name: 'George' }];
array[1] = { name: 'Simon' };
console.log(array);
.as-console-wrapper { max-height: 100% !important; top: 0; }
Edit, nearly, you could remove the actual item and add a new one, but this is in this case not advisable, because you take some array oreations, which are not necessay, like removing and inserting of an item.
arr.splice(1, 1, { name:'Simon' })
// ^ take one element out at index 1 and insert a new object
var array = [{ name: 'John' }, { name: 'Jane' }, { name: 'Smith' }, { name: 'George' }];
array.splice(1, 1, { name: 'Simon' });
console.log(array);
.as-console-wrapper { max-height: 100% !important; top: 0; }
2 Comments
Or if you just want to change the name:
arr[1].name = "Simon";
Comments
You can access elements directly by using sqaure brackets.
arr[0] will access the first element in the array so you need arr[1].
You can simply say arr[1] = {name:'Simon'}; to do this
The splice() method adds/removes items to/from an array, and returns the removed item(s).
spliceto replace the entry at a given location.