admin管理员组文章数量:1401673
I have an array stored in my local storage. It is dynamic. I'm storing the data along with an ID which gets incremented after every entry. User has an option of deleting, hence, I'm supposed to remove the corresponding element from the array. But, I want the ID to remain in ascending order. Ex:
var jsonObj = [{'id':'1','name':'Ray','email':'[email protected]'},
{'id':'2','name':'Steve','email':'[email protected]'},
{'id':'3','name':'Albert','email':'[email protected]'},
{'id':'4','name':'Christopher','email':'[email protected]'}]
I'm creating HTML divs for the above array. In case, Steve deletes his details, I want the array to be like:
var jsonObj = [{"id":1,"name":"Ray","email":"[email protected]"},
{"id":2,"name":"Albert","email":'[email protected]"},
{"id":3,"name":"Christopher","email":"[email protected]"}]
The following code doesn't work accordingly.
for (var i=0; i<jsonObj.length; i++) {
//delete function is working fine.
jsonObj[i].id--;
break;
}
I have an array stored in my local storage. It is dynamic. I'm storing the data along with an ID which gets incremented after every entry. User has an option of deleting, hence, I'm supposed to remove the corresponding element from the array. But, I want the ID to remain in ascending order. Ex:
var jsonObj = [{'id':'1','name':'Ray','email':'[email protected]'},
{'id':'2','name':'Steve','email':'[email protected]'},
{'id':'3','name':'Albert','email':'[email protected]'},
{'id':'4','name':'Christopher','email':'[email protected]'}]
I'm creating HTML divs for the above array. In case, Steve deletes his details, I want the array to be like:
var jsonObj = [{"id":1,"name":"Ray","email":"[email protected]"},
{"id":2,"name":"Albert","email":'[email protected]"},
{"id":3,"name":"Christopher","email":"[email protected]"}]
The following code doesn't work accordingly.
for (var i=0; i<jsonObj.length; i++) {
//delete function is working fine.
jsonObj[i].id--;
break;
}
Share
Improve this question
asked Feb 21, 2017 at 9:56
VenkyVenky
3403 silver badges15 bronze badges
1
- stackoverflow./questions/8310270/… – mplungjan Commented Feb 21, 2017 at 10:00
9 Answers
Reset to default 3You could just iterate from the given index and decrement the id
property.
function deleteItem(i) {
array.splice(i, 1);
while (i < array.length) {
array[i].id--;
i++;
}
}
var array = [{ id: '1', name: 'Ray', email :'[email protected]'}, { id: '2', name: 'Steve', email: '[email protected]' }, { id: '3', name: 'Albert', email: '[email protected]' }, { id: '4', name: 'Christopher', email: '[email protected]' }];
deleteItem(1);
console.log(array);
.as-console-wrapper { max-height: 100% !important; top: 0; }
If you start from 0, then you do not even need the ID
Ray is the 0th element, Christopher is 3rd
delete Albert and Christopher is 2nd
var jsObj = [{'name':'Ray','email':'[email protected]'},
{'name':'Steve','email':'[email protected]'},
{'name':'Albert','email':'[email protected]'},
{'name':'Christopher','email':'[email protected]'}]
for (var i=0;i<jsObj.length;i++) {
document.write("<br>ID"+(i+1)+": "+jsObj[i].name)
}
document.write("<hr/>");
jsObj.splice(2, 1); // Bye bye Albert
for (var i=0;i<jsObj.length;i++) {
document.write("<br>ID"+(i+1)+": "+jsObj[i].name)
}
More information
Reindex javascript array / object after removing a key
You just declare a new variable in your for loop which you will increment it and you assign this value as their id
for (var i=0, id=1; i<jsonObj.length; i++, id++) {
var jsonObj = [{'id':'1','name':'Ray','email':'[email protected]'},
{'id':'2','name':'Steve','email':'[email protected]'},
{'id':'3','name':'Albert','email':'[email protected]'},
{'id':'4','name':'Christopher','email':'[email protected]'}];
console.log(jsonObj);
jsonObj.splice(1, 1);
for (var i=0, id=1; i<jsonObj.length; i++, id++) {
jsonObj[i].id = id;
}
console.log(jsonObj);
a very simplistic approach could be:
// the index of the deleted element
const delIndex = 2;
// reindex all entries starting from deleted one
for (var i=delIndex+1; i<jsonObj.length; i++) {
jsonObj[i].id = i + 1;
}
The id basically corresponds with the array index anyway. So instead of trying to pute the id anew, we can just overwrite it with the respective index (+1 as you start with one and not zero like array indices).
for your requirements you have to use the splice method in the javascript
array.splice(index_you_wantto_delete,count)
ex:-jsonObj.splice(1,1);
The splice() method adds/removes items to/from an array,
Here is a verbose solution explaining the process step by step
1- Delete the element
2 - Update the indexes if the element was found and deleted
/**
*
* @param array list Your list
* @param int elementID The id of the element you want to remove
* @returns list The list with the element removed and the indexes rearanged
*/
var deleteElement = function (list, elementID) {
var removedIndex = false;
for (var index = 0; index < list.length; index++) {
if (list[index]['id'] === elementID) {
list.slice(index, 1);
removedIndex = index;
break;
}
}
if (removedIndex !== false) {
//Get last id
var lastElement = (removedIndex === 0) ? null : list[removedIndex - 1];
// Set to 0 if the first element was removed
var lastID = (lastElement === null) ? 0 : lastElement.id;
for (var i = removedIndex; i < list.length; i++) {
list[i].id = ++lastID;
}
}
return list;
};
Try the below method. Hope it works !!
// index of the deleted item
var itemDeleted = 2;
// create a for loop from deleted index till last
for (var i = itemDeleted-1; i < jsonObj.length; i++) {
jsonObj[i].id = i+1;
}
You can do in pure js by using map
const jsonObj = [{
'name': 'Ray',
'email': '[email protected]'
},
{
'name': 'Steve',
'email': '[email protected]'
},
{
'name': 'Albert',
'email': '[email protected]'
},
{
'name': 'Christopher',
'email': '[email protected]'
}
];
jsonObj.splice(1, 1);
const newObj = jsonObj.map((c, i) => ({
name: c.name,
email: c.email,
id: i + 1
}));
console.log(newObj);
Get the deleted index and assign it to the i
value of for loop
for (var i=deletedIndex; i<jsonObj.length; i++) {
jsonObj[i].id--;
}
本文标签: javascriptDecrement ID in JSON array after deletionStack Overflow
版权声明:本文标题:javascript - Decrement ID in JSON array after deletion - Stack Overflow 内容由网友自发贡献,该文观点仅代表作者本人, 转载请联系作者并注明出处:http://www.betaflare.com/web/1744237039a2596602.html, 本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌抄袭侵权/违法违规的内容,一经查实,本站将立刻删除。
发表评论