Reputation: 3091
I have an object that contains things i'm looking for:
1: Object [ ID: "38433" , Location: "Central"] 2: Object [ ID: "43434" , Location: "West"]
and I have a Object called Schools that contains the set of all things:
I am using the Object.keys()
method to loop through the object, but I need to pass in what Location to search to search in say Central, or West,etc. If I try to do something like (Schools.District.location) I get an error. How do i pass in the correct argument to my object.keys
function?
part2: What is the correct way to remove an element from that array. So i would need to remove Location[15] if say the ID's match.
Code:
$.each(Exclusions , function (index, value) {
var location = value.Location; //gives me Central, West, East
var ID = value.ID;
Object.keys(Schools.District.{{pass in location}}).forEach(function (key) {
//each location is an array of schools so i need to scan each for the matching ID
for (var i=0; i < {{get length of location array}}.length; i++) {
if(location[i][ID] == ID)
{
location.slice(); //not sure about this
}
}
});
Upvotes: 0
Views: 615
Reputation: 10762
You should use @am1r_5h's answer above. For each iteration, i
(I prefer to use key
though) is a proper key. (In the case of an array, an integer index.) Collecting the keys to use later is not idiomatic JavaScript.
Use the splice
method to delete from an array. It completely deletes the element and replaces it with nothing so that the new length of the array is original_length - 1
. Using delete
and passing the element index will replace the element with undefined
while the length of the array remains the same. Here's the docs for Array.prototype.slice
: https://developer.mozilla.org/enUS/docs/Web/JavaScript/Reference/Global_Objects/Array/splice
Upvotes: 1
Reputation: 2083
you want to use objects.key
certainly ? why dont you use a for in
?
var result = [];
for (i in YOUR_OBJECT)
{
if(YOUR_OBJECT[i].location == "what you want") result.push(YOUR_OBJECT[i]);
}
i guess you can not remove property you want probably, but you can set that to null
, and at the end, get those property that its not null
EDIT: to delete a property on YOUR_OBJECT: (i is a key iterator)
delete YOUR_OBJECT[i]
Upvotes: 1