Get array key to remove an array based on that array object - arrays

New question, so this is the array
[
0: {
"id" : "3"
"name": "David",
"age": "20"
},
1: {
"id" : "6"
"name": "",
"age": "18"
},
2: {
"id" : "8"
"name": "Micheal",
"age": "25"
},
3: {
"id" : "9"
"name": "Wonder Women",
"age": "20"
},
4: {
"id" : "12"
"name": "Clark",
"age": ""
}
]
How to delete based on id when I click a button? In my app have a delete button to delete this array. I think it need to get array key in order to delete the array.
For example: I can get the id=8, but how can i get array key 2 to delete number 2 array?
If you don't understand, please welcome to comment. Thanks.

array.filter((obj) => {
if (obj.id != yourId){
return obj;
}
})
and don't forget all commas in your objects in array. (after id)

if you want to directly manipulate the contents of an array instead of returning new array, you can try this
let index = array.findIndex(obj => obj.id == objIdToDelete)
if(index != -1) { array.splice(index, 1) }
check Array.prototype.splice() to know more

Suppose your array is like:
arr = [
{"id":"3","name":"Clark"},
{"id":"6","name":"David"},
{"id":"8","name":"Miche"}
];
id = 6;
arr = $.grep(arr, function(data, index) {
return data.id != id
});
Now finally this will return array with removing record of id=6

Suppose your array was stored in obj, you can use lodash function remove to remove an item in an array in the following way.
_.remove(obj, function(currentObject) {
return currentObject.id == "8";
});
Which will remove the item '2' containing '8' from your array

Related

Return one array of data in sub-document of Mongodb

I'm using Nodejs with Mongoose package.
Given I've something like this:-
let people = [
{
"_id": 1,
"name": "Person 1",
"pets": [
{
"_id": 1,
"name": "Tom",
"category": "cat"
},
{
"_id": 2,
"name": "Jerry",
"category": "mouse"
}
]
}
]
I want to get only the data of Jerry in pets array using it's _id (result shown below)
{
"_id": 2,
"name": "Jerry",
"category": "mouse"
}
Can I get it without needing to specify the _id of person 1 when using $elemMatch? Right now I code like this:-
const pet = People.find(
{ "_id": "1"}, // specifying 'person 1 _id' first
{ pets: { $elemMatch: { _id: 2 } } } // using 'elemMatch' to get 'pet' with '_id' of '2'
)
And it gave me what I want like I've shown you above. But is there any other way I can do this without needing to specify the _id of it's parent first (in this case, the _id of the people array)
Assuming nested array's _id's are unique you can filter by nested array elements directly:
const pet = People.find(
{ "pets._id": 2 },
{ pets: { $elemMatch: { _id: 2 } } }
)

How to remove an element from a json with ruby?

For this json structs:
{
"a_path": {
"b_path": [
{
"id": 1,
"name": "a"
},
{
"id": 2,
"name": "b"
}
]
}
}
Want to remove id element as:
{
"a_path": {
"b_path": [
{
"name": "a"
},
{
"name": "b"
}
]
}
}
Is there a good way? I have tried:
$json_data = JSON.parse(response)["b_path"][0].delete("id")
But got this result:
"a_path": "1"
Even if .delete would return the mutated hash (which it doesn't, it returns the deleted value), you are assigning $json_data = JSON.parse(response)["b_path"][0].
Just assign the base hash, and mutate it in a loop with .each.
json_data = JSON.parse(response)
json_data['a_path']['b_path'].each { |h| h.delete('id') }
json_data
# => the expected hash
Try the .delete method. It shoud return you the mutated hash but in actual it returns the deleted value. So only way is you need to assign the base hash and mutate it in a loop and call .delete within that

Merge Multiple Array by keys - Angular 5, Typescript

My question is about typescript and not javascript. I want to merge multiple arrays by key(id). For Example: I have these one to many relations arrays
Student Array 1 :
[
{
"Case ID":12,
"Student name":"john",
"address":"Ohio"
},
{
"Case ID":13,
"Student name":"David",
"address":"new york"
}
]
Courses Array 2 :
[
{
"id":34343,
"Case ID":12,
"course":"algorithm",
"Grade":"A"
},
{
"id":343434,
"Case ID":12,
"course":"advanced c++",
"Grade":"B"
}
]
I want to get this array which has keys from both array1 and array 2 :
`[
{
"Case ID":12,
"name":"john",
"Courses":[{"course":"algorithm",
"Grade":"A",},
{"course":"advanced c++",
"Grade":"B"}]
}
]`
#JohnyAli, you don't want get the object that you propouse (they have a repeted key). You want to get
{ Sid:..,name:..,courses:[{Grade:..course:..},{Grade:..course:..}]
So use map
const data=this.students.map(x=>{
//witch each element of students
return { //an element that have
Sid:x.Sid, //property Sid equal property Sid of element
name:x.name, //idem with name
courses:this.courses.filter(c=>c.Sid==x.Sid) //the variable courses
//was the courses where
//Sid was equal the Sid of element
})
_.groupBy() lodash will do that job, you can have any property you want to group by your array.
var arr = [
{
"name": "xyz",
"age": 22,
"add": "street 5"
},
{
"name": "fjf",
"age": 22,
"add": "street 6"
}
];
console.log(_.groupBy(arr, 'name'));
/** result:
{
"xyz": [
{
"name": "xyz",
"age": 22,
"add": "street 5"
}
],
"fjf": [
{
"name": "fjf",
"age": 22,
"add": "street 6"
}
]
} **/
You can use lodash
and do the merge opeartion on both the arrays to a destination array.

How to know array contents are empty

Lets say I have array like this :
[
{
"id" : "1"
"name": "David",
"age": "20"
},
{
"id" : "2"
"name": "",
"age": "18"
},
{
"id" : "3"
"name": "Micheal",
"age": "25"
},
{
"id" : "4"
"name": "Wonder Women",
"age": "20"
},
{
"id" : "5"
"name": "Clark",
"age": ""
}
]
Some of the contents are empty. How to write the condition if "age" is null and "name" is null.
You can filter the array and then use it where you need:
const myFilteredArray = arr.filter(item => {
return item.name !== null && item.age !== null
})
// use myFilteredArray in your code.
As your request is not definitive, I'm assuming you want the person elements that satisfy your criteria in a new array, called personsWithoutNameAndAge.
You can achieve this very elegantly, using functional programming:
const personsWithoutNameAndAge = persons.filter(person => !person.name && !person.age)
The filter() method creates a new array with all elements that pass the test implemented by the provided function.
The function we provide the filter function (the argument passed to it) only passes the test (returns true) if both person.name and person.age are falsy. Empty string, undefined, and null are all falsy and so the function will successfully work with any of these values representing 'null'.
Hope this helps!

angularJS scope orderBy does not sort children, just the parent

When I used
$scope.data = $filter('orderBy')(data,'title');
the parent is sorted, the children are not.
What if my array has children? how can I order the parent and the children?
My array:
data = [
{
"id": 1,
"title": "abc",
"items": [
{
"id": 3,
"title": "abc2",
"items": []
},
{
"id": 4,
"title": "abc1",
"items": []
}
]
},
{
"id": 2,
"title": "cde",
"items": [
{
"id": 5,
"title": "cde2",
"items": []
},
{
"id": 6,
"title": "cde1",
"items": []
}
]
}
]
Thanks in advance.
It shouldn't sort anything within the child's objects.
For sorting within child object sort your 'items' recursively, for each child, with $filter('orderBy') or similar with code bellow use your own custom comparing function.
var orderByFieldName = 'title',
childPropertyForSorting = 'items',
s = function (a, b) {
//Revise comparing function depends on direction of sorting and your wishes
if (a[orderByFieldName] > b[orderByFieldName])
return 1;
if (a[orderByFieldName] < b[orderByFieldName])
return -1;
return 0;
},
f = function (o) {
if (o.hasOwnProperty(childPropertyForSorting) && o[childPropertyForSorting] instanceof Array) {
o[childPropertyForSorting].sort(s);
o[childPropertyForSorting].forEach(f);
}
};
if (originalData instanceof Array) {
originalData.sort(s);
originalData.forEach(f);
}
I would suggest if you are only trying to orderBy in the view to use
data-ng-repeat="item in data | orderBy: 'colum you want'"
Read more about it here
Reason is the children is in another level and treated just as another key value pair inside that object, you can use the same filter you used inside a for loop that will loop each data array item and sort the children like this :
//filter the parent level by title
$scope.data = $filter('orderBy')(data,'title');
//copy the sorted array in temp variable
var temp = angular.copy($scope.data);
//sort the children by title while aggregating each array item and then storing the output in $scope.
for(var i=0;i<data.length;i++){
$scope.data[i].items = $filter('orderBy')(temp[i].items,'title');
}

Resources