delete an item in an object array by id [duplicate] - javascript

This question already has answers here:
Find and remove objects in an array based on a key value in JavaScript
(14 answers)
Closed 1 year ago.
I want to delete an item based on its id.
I retrieve id from the cell where I click but I don't know how to retrieve id in the array to be able to compare it to that of the click to delete only the one selected and not all of the array, I'm not sure which method to use
My item.json
[{
"id": "e3c387fd-7cf1-4d5b-9825-cef745c0ab99",
"name": "item 1",
"fans": {},
"cell": [{
"id": "e2021621-9c74-4960-bf47-f6ad917ee40b",
"name": "cell 1 item 1",
},
{
"id": "d5129940-716c-47a3-81b5-f2c90e69b602",
"name": "cell 2 item 1",
}
]
},
{
"id": "79fe939b-4c64-4b73-bebd-6563f445920c",
"name": "item 2",
"fans": {},
"cell": [{
"id": "7b6b57c6-7b72-4a14-8932-51fc2e5f9b75",
"name": "cell 1 item 2",
},
{
"id": "b579f94f-605e-4c7a-a8c5-3aad9bfec9e2",
"name": "cell 2 item 2",
}
]
}
]
My function
trashItem(id) {
this.cellsListsData = this.cellsListsData.filter(cell => {
cell.id === id, console.log(cell.id, id);
});
}

this.cellsListsData = this.cellsListsData.filter(function(element) {
return element.id !== id;
});
or Just Get the index of it and then this.cellsListsData.splice(index, 1);

This would require traversing through the whole array and finding the index of object with the given id. Once you find the id, you can simply splice the array from that index with offset 1.
Below is a quick snippet for doing that.
var index_to_delete;
data.forEach(function(value, index) {
if (value.id == id_of_clicked_element) {
index_to_delete = index;
};
});
data.splice(index_to_delete, 1);
Note: Using filter will create a new array. So, if you are referencing the data array in some other variables, they will not get the new array. So, I recommend using the filter solution with caution. Also, some answers say to delete element at that index. This would remove that index from array and your array will be rendered inconsistent.

Related

how to sort an array by dates in a nested array

I have an array of objects being returned from a REST API. Each of these objects contains it's own array too, like this:
{
"content": [
{
"id": 1,
"name": "Name 1",
"data": [
{
"id": "klqo1gnh",
"name": "Item 1",
"date": "2019-05-12"
}
]
},
{
"id": 2,
"name": "Name 2",
"data": [
{
"id": "klqo2fho",
"name": "Item 1",
"date": "2021-05-05"
},
{
"id": "klro8wip",
"name": "Item 2",
"date": "2012-05-05"
}
]
}
]
}
I then map over the data, and return it, like this (this is a very stripped down example):
{content.map((item) => {
return (
<div>
{item.name}
{item.date}
{item.id}
</div>
);
})}
Much like you'd expect. What I need to do, however, is sort this by date, preferably using Moment.js, finding the item in the array that contains the earliest date, and then displaying that item first. For example, item "id": 2 contains the date 2012-05-05, and since that's the earliest date in the data, I need that item to be first. I'm really lost here, Moment's documentation isn't super clear.
Thanks in advance.
You could make a function which takes an array of items as a parameter and returns a new array sorted by date, using Moment.js, could be something like this:
function sortByDate(items: any[]) {
return items.sort((first, second) => {
if (moment(first.data.date).isSame(second.data.date)) {
return -1; // If they have the same date, return the first item
} else if (moment(first.data.date).isBefore(second.data.date)) {
return -1; // If the first date is earlier, return the first item
} else {
return 1; // The second date is earlier, so it goes first;
}
})
}
Then you can use this function before mapping content
Did you ever use the sort method of the JavaScript array?
array.sort((a, b) => a.value - b.value)
If a.value - b.value is bigger than 0, then b is former item than a.

Unable to delete an array index/item using delete [duplicate]

This question already has answers here:
How can I remove a specific item from an array in JavaScript?
(142 answers)
Deleting array elements in JavaScript - delete vs splice
(29 answers)
Closed 3 years ago.
I am using delete in order to try to delete an item on an array;
const handleRowDeletion = index => {
const inputsAdded = shareStructureInputs;
const inputs = startupFourthStepForm.shares_estructure;
delete inputs[index];
delete inputsAdded[index];
}
I can see the first array inputsAdded getting deleted at the proper index but not the second one inputs.
This is what inputsAdded returns:
[
"share-structure-input-0",
"share-structure-input-1",
"share-structure-input-2"
]
And inputs:
[
{
"name": "Name 1",
"percentage": 10
},
{
"name": "Name 2",
"percentage": 10
},
{
"name": "Name 3",
"percentage": 80
}
]
And I call the function on a map
<Button onClick={() => handleRowDeletion(index)}>
- Delete Row
</Button>

Get the last elements in a JSON array in Javascript

I have a JSON array like this:
[
{
"id": "1",
"name": "A"
},
{
"id": "2",
"name": "B"
},
{
"id": "3",
"name": "C"
},
{
"id": "4",
"name": "D"
},
....
....
{
"id": "n",
"name": "X"
}
]
I'm looking for a slice() based function that gives the last 20 item of this JSON array
function getLast(array,x){return array.slice(array.length-x)}
Just use the slice function starting with the array length minus the number of elements you want to extract.
A simple way with filters:
filteredList = list.filter((_, index) => {
return index >= list.length - 20
})
If you just need the last X items in an array I'm not sure you need filter, you can use .slice eg [1,2,3,4,5,6,7,8,9,10].slice(-5) will return [6,7,8,9,10]
One option is to use splice or slice:
// Initialize array
let arr = new Array(50).fill().map((v,i)=>i)
// Pick off last 20 elements
console.log('Last:' + arr.slice(-20))
Note: splice modifies the existing array; if you don't want to modify the existing array use slice
Another example
let arr = new Array(50).fill().map((v,i)=>i+1) // [1,2,..50]
Array.prototype.last = function(n){
return this.slice(-n)
};
console.log( arr.last(20) )

React element - array objects only returning first item?

I am trying to retrieve item values from an object containing several items. The object is an array object. I am puzzled by only being able to retrive the first item and its values in each array instead of all items. Can anybody tell me what I am missing here.
The array object example:
{ "ITEM 1": [
{
"id": 123,
"name": "item1a"
},
{
"id": 234,
"name": "item1b"
},
{
"id": 345,
"name": "item1c"
}
],
"ITEM 2": [
{
"id": 456,
"name": "item2a"
},
{
"id": 567,
"name": "item2b"
},
{
"id": 678,
"name": "item2c"
}],
}
I have data within the new element and on debugging see that loop flows correctly but for some reason only the first item is rendered.
My code that is wrapped in an html element is as follows:
{ Object.keys(this.props.data).map(function (key) {
var list = component.props.data[key];
for (i = 0; i < facetParent.length; i++) {
var item = list[i];
return (
<CheckBox
key={item.id}
data={item}
name={item.name} />
)
}}, this)}
Any suggestions are much appreciated.
The return function immediately terminates the function execution. That is why you only get the first item. Depending on what version of react you use, you should create 2 arrays and join them before rendering

check json object exist to be save into localstorage

[
{
"id": 1,
"title": "my Item",
"body": ""
},
{
"id": 2,
"title": "my Item 2",
"body": ""
},
{
"id": 3,
"title": "my Item 3",
"body": ""
}
]
Is above json structure good for storing says users viewed books? I have other key like users' setting so I try to nested/group things to be neater. My question is how can I check an object with value exist or not so I won't insert duplicated data. How to check the id 2 is existed in this case? Do I have to loop?
Do I have to loop?
Yes you have to loop ( or use a method which will do it) :
var idToCheck="id";
var valToCheck=2;
var a = your array...
var wasFound=false;
a.forEach(function(entry) {
if (entry[idToCheck]==valToCheck)
{
wasFound=true;
return;
}
});
//do whatever with `wasFound`.
http://jsbin.com/jigefamiqu/1/edit

Categories

Resources