remove specific line from json with jquery - javascript

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);

Related

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/

Selecting javascript objects via their methods with jquery

How would I select:
object.id2 == "name1";
with jQuery (instead of looping through all of the objects and finding the one who's id2 matches "name1"), so I could write something like:
$("name1");
or maybe:
$(object + " name1");
or possibly:
$(object).attr('id2','name1');
You can use Lodash:
var namedObjects = _.find(allObjects, { id2: 'name1' });
var myObj = $('[id2="name1"]')
//myObj will be an array if there is more than one element that matches
As seen here: jQuery Selector API
This might not be the best way to do it, but if you insist on doing it with jquery, this would be the way to do it:
var theArr = [{id2:"name0"},{id2:"name1"}];
var myObj = $(theArr).filter(function(){
return this.id2 === "name1";
}).get(0);
console.log(myObj); // Object {id2: "name1"}
http://jsfiddle.net/Tentonaxe/kTxkr/
of course, if you don't have to support IE<9, you can cut jquery out without changing much:
var theArr = [{id2:"name0"},{id2:"name1"}];
var myObj = theArr.filter(function(obj){
return obj.id2 === "name1";
})[0];
console.log(myObj); // Object {id2: "name1"}
http://jsfiddle.net/Tentonaxe/kTxkr/1
I'm not sure I completely understand your question, but if you create an object like this:
var foo = {id2 : "name1"};
You can use a jQuery selector like this:
$(foo)

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

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];
}
}

jQuery .each help, I want to trim() all the strings in an array

I'm splitting a string into an array, then I want to remove the white space around each element. I'm using jQuery. I'm able to do this successfully with 2 arrays but I know it's not correct. How do I loop thru an array and trim each element so the elements keep that change. Thanks for any tips. Here is my working code using two array. Please show me the correct way to do this.
var arVeh = vehicleText.split("|");
var cleanArry = new Array();
$.each(arVeh, function (idx, val) {
cleanArry.push($.trim(this));
});
Cheers,
~ck in San Diego
You don't even really need the idx or val parameters. This appears to work on jsFiddle:
var cleanVehicles = [];
$.each(vehicleText.split("|"), function(){
cleanVehicles.push($.trim(this));
});
EDIT: Now that I've seen what you're really after, try using map:
var cleanVehicles = $.map(vehicleText.split("|"), $.trim);
I'm going to suggest not using the overhead of jQuery for a simple for-loop...
var arVeh = vehicleText.split("|");
for (var i = 0, l = arVeh.length; i < l; ++i) {
arVeh[i] = $.trim(arVeh[i]);
});
Alternatively, get rid of the whitespace from the beginning, and avoid the need for another loop at all.
var arVeh = $.trim(vehicleText).split(/\s*\|\s*/);
Without 'creating' an array in the javascript code (an array will nevertheless be created in memory)
vehicles = $.map(vehicleText.split("|"), function(e,i) { return $.trim(e) });
var my_arr = [' cats', 'dogs ', ' what '];
$.each(my_arr, function (id, val) {
my_arr[id] = $.trim(val);
});
console.log(my_arr);
This will trim the value and set it to the indexed item.
You don't have to use JQuery. Here is your vanilla solution:
testArray.map(Function.prototype.call, String.prototype.trim);
Function.prototype.call calls trim() on each of the elements of the testArray. As simple as that!
Could you not just do this?
var arVeh = vehicleText.split("|");
$.each(arVeh, function (idx, val) {
arVeh[idx] = $.trim(this);
});
//a simple function
function trimArray(dirtyArray){
$.map(dirtyArray.split("|"), function(idx, val){
return $.trim(this);
});
}
trimArray(vehicleArray);
should do the trick
Or you could use some of the awesome power of javascript and use array.prototype. I'm still a little new at using the .prototype of any object... so this isnt guaranteed to work (but it certainly can be done).
Array.prototype.trim = function (){
$.map(dirtyArray.split("|"), function(idx, val){
return $.trim(this);
});
}
someArray.trim()
You need these two jQuery functions:
1.) iterate through array element with ability to edit items:
http://api.jquery.com/jquery.map/
2.) remove blank spaces from beginning and end of a string:
http://api.jquery.com/jQuery.trim/
Use them this way:
array = $.map(array, function(value) { return value.trim();});
Check this JSFiddle:
https://jsfiddle.net/L00eyL4x/49/

Javascript: Convert textarea into an array

How would you go about breaking up a textarea value into an array, based on the end of line separation? Use of jQuery is cool by me...
This should work (tested in Firefox and Google Chrome):
var arrayOfLines = $('#textAreaID').val().split('\n');
Cross-platform way:
var area = document.getElementById("area");
var lines = area.value.replace(/\r\n/g,"\n").split("\n");
var stringArray = document.getElementById('textarea').value.split('\n');
I like the "cross-platform way" answer best (https://stackoverflow.com/a/32240738/34806) as I've grappled with input from a Mac in the past. Nevertheless I think most of the existing answers could benefit from an additional step.
Specifically, what if some lines are empty? The following will filter out such lines so that we wind up with a "compact" array rather than a "sparse" one (or at least, rather than one with elements containing no values)
var area = document.getElementById("area");
var lines = area.value.replace(/\r\n/g,"\n").split("\n").filter(line => line);
You could try this function :
function textToArray(){
var someArray = [];
var nameList = $("#txtArea").val();
$.each(nameList.split(/\n/), function (i, name) {
// empty string check
if(name != ""){
someArray.push(name);
}
});
taken from : CONVERT TEXTAREA CONTENT TO AN ARRAY USING JQUERY
This method worked well:
var textArea = document.getElementById("textAreaId");
var arrayFromTextArea = textArea.value.split(String.fromCharCode(10));

Categories