Javascript: Removing an object from array by checking it's attribute - javascript

I might have written a pretty confusing title but my question is rather simple.
I'm looking for an efficient way to remove an item from an array. But my array is full objects that has been stringified (I'm writing my app on Node.js and I'm using JSON.stringify method). So my array is like this;
"{\"userID\":\"15\",
\"possibleFollowers\":[
{\"followerID\":\"201\",\"friends\":716},
{\"followerID\":\"202\",\"friends\":11887},
{\"followerID\":\"203\",\"friends\":11887}],
\"name\":\"John\",
\"lon\":\"Doe\"}"
My question is on Javascript(or Node). If I wanted to remove the from possibleFollowers with "followerID: 202", how would I be able to do that efficiently?

var string = "…";
var obj = JSON.parse(string);
obj.possibleFollowers = obj.possibleFollowers.filter(function(fol) {
return fol.followerID != "202";
});
string = JSON.stringify(obj);

var data = "{\"userID\":\"15\",\"possibleFollowers\":[{\"followerID\":\"201\",\"friends\":716},{\"followerID\":\"202\",\"friends\":11887},{\"followerID\":\"203\",\"friends\":11887}],\"name\":\"John\",\"lon\":\"Doe\"}";
var dataObject = JSON.parse(data);
dataObject.possibleFollowers = dataObject.possibleFollowers.filter(function(follower) {
return !(follower.followerID == "202");
});
data = JSON.stringify(dataObject);

In javascript, the splice method is used to delete an array element by index.
see :
http://www.roseindia.net/java/javascript-array/javascript-array-remove-index.shtml

try just to delete it by using "delete"
for (var i in possibleFollowers) {
if (possibleFollowers[i]['followerId'] == '216') {
delete possibleFollowers[i];
}
}

Related

Adding values to a specific property in an array(?) in javascript

Im wondering how I can add a value to to main in this array.
var herpderp = {
"main": ["stuff", "stuff"]
};
so it would look like:
var herpderp = {
"main": ["stuff1", "stuff2", "stuff3"]
};
Preferably I'd like to create this kind of structure from a couple of strings in a fucntion if that's possible. So says I have this
var strings = {"stuff1","stuff2", "stuff3"}
for (each element of strings) {
what do I do here to get the structure above
}
Alternatively another function to search through an Array of objects on a specifik property. Right now Im trying to use this to filter through the array, maybe there's another way?
var arrays = search;
var result = events.filter(function(item) {
for (var prop in arrays)
if (arrays[prop].indexOf(item[prop]) == -1)
return false;
return true;
});
Thank you kindly for any reply!
herpderp.main is your array, so you can add to the array like so:
herpderp.main.push(value)
If the key for your array was not a valid variable name (it starts with a number, for example), you could use bracket notation instead:
herpderp['123key'].push(value)
Actually, you are changing the previous values beside adding a new element.
var herpderp = {
"main": ["stuff", "stuff"]
};
var strings = ["stuff1","stuff2", "stuff3"];
strings.forEach(function(value,key){
herpderp.main[key] = value;
});
console.log(herpderp);

how to find specific objects and put them in an array in javascript

I have this result in my script
'[{"region":"NCA","depprt":"Havana, Cuba"},{"region":"NCA","depprt":"Havana, Cuba"},{"region":"NCA","depprt":"Montego Bay, Jamaica"},{"region":"NCA","depprt":"Montego Bay, Jamaica"}]'
this is the code to get it.
var jsonList = '#Html.Raw(Json.Encode(ViewBag.chk))'
var jsList = JSON.stringify(jsonList);
for jsList I got above result.now I want to get all depprt where region is equal to NCA.how can I do that.
You can use the .filter() method for this.
var ncaList = jsonList.filter(function(obj){ return obj.region == "NCA"; });
Very simple. Iterate over the jList array and see if the region property matches your condition or not then append the item to your filtered array.
var filtered = [];
jList.forEach(function(item) {
if(item.region == 'NCA') {
filtered.push(item);
}
});
Just iterate over it:
var filteredDepprts = [];
jsList.forEach(function(element){
if(element.region == 'NCA'){
filteredList.push(element.depprt); //or element if you want to push the full object
}
});
The JSON.stringify method converts a JavaScript value to a string.
https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/JSON/stringify
When you want to convert a JSON string to a JavaScript value, use JSON.parse
https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/JSON/parse
var jsonList = '#Html.Raw(Json.Encode(ViewBag.chk))'
var jsList = JSON.parse(jsonList);
Using single quotes around your #Html.Raw, creates a string and not a JavaScript value. The filter method does not work on strings
Eventually you could use Array.prototype.filter Filter out each element in array, that matches your criteria.
https://developer.mozilla.org/nl/docs/Web/JavaScript/Reference/Global_Objects/Array/filter
Try map:
var obj= [];
for (i in jsonList) {
if (jsonList[i].region == "NCA") { obj.push(jsonList[i])};
}
https://jsfiddle.net/pd6hvn78/

Find specific key value in array of objects

This is the code:
var groups = {
"JSON":{
"ARRAY":[
{"id":"fq432v45","name":"Don't use me."},
{"id":"qb45657s","name":"Use me."}
]
}
}
I want to get the name value where the id is "qb45657s" how could this be accomplished? I figured the obvious loop through all of the array and check if it's equal but is there an easier way?
Edit: I cannot change "Array" to an object because I need to know the length of it for a different function.
You can simply filter on the given id:
groups["JSON"]["ARRAY"].filter(function(v){ return v["id"] == "qb45657s"; });
This will return [{"id":"qb45657s","name":"Use me."}]
Assuming you had a valid JSON string like this (note I say valid, because you need an enclosing {} or [] to make it valid):
var json = '{"JSON":{
"ARRAY":[
{"id":"fq432v45","name":"Don't use me."},
{"id":"qb45657s","name":"Use me."}
]
}
}';
You would just parse it into an actual object like this:
var jsonObj = JSON.parse(json); // makes string in actual object you can work with
var jsonArray = jsonObj.JSON.ARRAY; // gets array you are interested in
And then search for it like:
var needle = 'qb45657s';
var needleName;
for (var i = 0; i < jsonArray.length; i++) {
if (jsonArray[i].id === needle) {
needleName = jsonArray[i].name;
}
}

remove specific line from json with jquery

I have this array:
var array = [{"a":"1","b":"2"},{"a":"3","b":"1"},{"a":"5","b":"4"}]
now i want to remove the line, lets say, where a=5. So afterwards the array looks like this:
var array = [{"a":"1","b":"2"},{"a":"3","b":"1"}]
How do i do this the easiest and fastest way?
You can use jQuery.map which allows you to return null for an element to be deleted.
eg:
var array = [{"a":"1","b":"2"},{"a":"3","b":"1"},{"a":"5","b":"4"}]
var newArray = $.map(array, function(e){
return (e.a == "5") ? null : e;
});
// newArray contains [{"a":"1","b":"2"},{"a":"3","b":"1"}]
Live example (watch the console): http://jsfiddle.net/2Yz7f/
Javascript (non jQuery) approach: http://jsfiddle.net/VYKBc/
Maybe this is your answer
array.splice(2,1);

jQuery inArray with Hashtable

I'm using a hash table and I'm trying to check for object existence. However I haven't been successful in figuring out how to do this. Could someone help guide me with this. Thanks.
current code.
When clientId equals field id and has item id return true, else add to saved_tokens.
var saved_tokens = {};
if ($.inArray(item.id, saved_tokens) == -1) {
saved_tokens.push[clientId] = item.id;
}
Don't use jQuery for that. Use pure JavaScript:
if (!saved_tokens.hasOwnProperty(clientId)) { // If clientId is not in the hash
saved_tokens[clientId] = item.id;
}
.push is an array method. A {} creates an object. Since this object is not an array, it doesn't have any array methods.
I personally use 'typeof'.
var saved_tokens = {};
if (typeof(saved_tokens[clientId]) == 'undefined') {
saved_tokens[clientId] = item.id;
}

Categories