Remove an object from an array on a condition - javascript

I have a csv file that I've already splitted by line breaks and I've broken it down even more by the commas in the line breaks to give me three things I'm looking for and named them for later use in the program. What I'm looking to do is remove an item if a one of the objects match a certain value.
var values=[];
var output="";
for(i = 0; i < csv_split.length; i++){
csv_split[i] = csv_split[i].split(',') //Splits the csv file that's already split by new line by commas
values[i]={}
values[i].Name=newline_split[i][1]; //finds the second object and names it values.name
values[i].Rev=newline_split[i][2]; //finds the third object and names it values.rev
values[i].URL=newline_split[i][9]; //finds the eighth object and names it values.url
}
This then is used later so I can get a list of just the values I'm looking for.
for (i=0; i < values.length; i++){
output += values[i].Name + ',';
output += values[i].Rev + ',';
output += values[i].URL+ ',';
output += "\n\n||||||";
}
So what I did was modified this code to the first for loop:
if (values[i].Rev == "NO ACCESS") {
csv_split[i].splice(0,1);
}
The idea behind this was that if the values.Rev matched to "NO ACCESS" it would remove the entirety csv_split[i], so that later it wouldn't display it in the output.
Running the script now gives the entire output of regardless if values.Rev matches "NO ACCESS" or not. What am I missing with this?

You could do this much easier with the filter method. You use it like this:
var finalArr = values.filter(function(val) { return val.Rev != "NO ACCESS"; });
This should give you an array of everything that has access.

Related

Split json data using comma

I have a json which has a key "tag", which is returning data like this
"tags": "jname,gender,city"
but i want to append these value in separate span like below
<div class="info">
<span>jname</span><span>gender</span><span>city</span>
</div>
I am trying with this
$.getJSON("data.json", function(tagsposts) {
var items = [];
splitsVal = tag.split(",");
for (var i = 0; i < splitsVal.length; i++) {
obj.push({name:splitsVal[i]});
obj[i] = '<span>' + obj[i] + '</span>';
$('.tags-div').append(obj[i])
}
$.each(tagsposts, function(key, val) {
items.push('' + val['tags'] + '');
});
$('#tagsposts').append(items.join(""));
});
Am I doing correct
You're trying to split an undefined variable:
function(tagsposts) {
var items = [];
splitsVal = tag.split(","); // but tag doesn't exist...
(If you look at your browser console, which you should get into the habit of doing, you'll get a very clear message about why this isn't working: "ReferenceError: Can't find variable: tag".)
Since you haven't provided your JSON it's not possible to say exactly how to fix this. Assuming the full JSON is of the form
{"tag": "foo,bar,baz"}
then you would want
splitsVal = tagsposts.tag.split(",")
If there's more structure than that inside the JSON, you'll need to crawl down through that parsed object to find the "tag" value(s) you need.
There are lots of other problems here, however.
You also try to push onto an undefined array named obj; you'd need at least a var obj = [] outside that for loop. Though it's not clear why you're using obj at all, or trying to draw an object {name: val} into the DOM instead of just the value. What you're trying to do is just read splitsVal[i] so you can just do this:
for (var i = 0; i < splitsVal.length; i++) {
$('.tags-div').append('<span>'+splitsVal[i]+'</span>')
}
And you try to iterate over tagsposts as if it's an array when generating the #tagsposts contents. (Is your JSON an array? If so you need to iterate over it when getting the tag values too.)

find and remove words from a string that's initiated in database

It's my first time working with database using socket.io and I keep running into a problem.
I have a number of objects in my database labeled as "artid,artimg,artimg". Artid has multiple entries that were labeled "Artifact001", "Artifact002", "Artifact003" etc. I'm trying to remove the word "Artifact" from the string leaving only numbers. But when I'm trying to use .replace expression it messes up with the line localStorage.getItems() instead of what's inside 'artid'. Is it possible to edit artid, or would I have to do it directly in the database? Please advise.
socket.on('toClient', function (data) {
for (var i = 0; i <data.DBarray.length ; i++) {
console.log(data.DBarray[i]);
localStorage.setItem(i.toString()+"artid", data.DBarray[i].artid);
//omit other values for now
}
});
$(document).ready(function() {
console.log('localStorage length: ' + (localStorage.length)/8);
for (var i = 0; i < (localStorage.length)/8; i++) {
$("ul").append("<li><h3 class='artifact_id'>"+localStorage.getItem(i.toString()+'artid')+"</h3></li>");
artid = artid.replace(/ *\b\S*?Artifact\S*\b/g, '');
}
In your for...loop try this:
artid = localStorage.getItem(i.toString()+'artid').replace(/ *\b\S*?Artifact\S*\b/g, '');
$("ul").append("<li><h3 class='artifact_id'>"+artid +"</h3></li>");
That should grab the value from localStorage, strip out the artifact and store it into a variable, which you can print onto the page.

Getting the data from json object in javascript

I have this object from a PHP API:
[Object { span=1, caption="Particular", master=true},
Object { span=5, caption="Loan Class 1"},
Object { span=5, caption="Loan Class 2"},
Object { span=5, caption="Loan Class 3"}]
The desired output would be:
## Particular Loan Class 1 Loan Class 2 Loan Class 3 ##
I tried to do this :
var arrData = typeof JSONData != 'object' ? JSON.parse(JSONData) : JSONData;
for (var index in arrData[0]) {
row += index + ',';}
row = row.slice(0, -1);
CSV += row + '\r\n';
What the csv looks like
## span caption master ##
Please help how to get the caption value and if there's a script that will output this in excel since there is a need to add some merging of columns.
You should be iterating over the whole array, not just the object in arrData[0]. And you should not use for (index in object), that just sets index to the keys, not the values. Then to access the captions, you use .caption.
for (var i = 0; i < arrData.length; i++) {
row += arrData[i].caption + ',';
}
For the caption part you could use this:
var row = arrData.map(function(element) {
return element.caption;
}).join(' ');
.map is used to extract the caption value of all elements in the array. The resulting array values are concatenated with .join. You can specify the separator as a parameter for the .join function.
Writing anything in Excel file format is not trivial. Unless you want the result in CSV format (which your code example implies). For that you might want to take a look at this answer.

Get first property key of JSON for a TreeView

Thanks for the answers on the previous two questions. I have a new one, and this one is a collapsible panel in jQuery. The concept is, the first key of a JSON object will appear as a button, and the other keys will be treated as regular text like <p> and the like.
I have this function which tests for the first index of an object.
function isFirstIndex(obj){
var key;
for(key in obj){
if(obj[key]===0){
return true;
}
}
return false;
}
I have tried this one:
function generateTree(data, selId){
var cnt = "";
for (var i=0; i<5; i++){
var row = data[i];
$.each(row, function(key,value){
if (isFirstIndex(row)){
cnt += "<button>" + value + "</button><br/>";
} else{
cnt += "<strong>" + key + "</strong> :" + value + "<br/>";
}
});
cnt += "<br/>";
}
$(selId).html(cnt);
}
But eventually found out in debugging that the key in the isFirstIndex function is compared with a string.
Suppose I have a JSON :
{"userId" : 1, "name" : "cool name"}
I want to show the first key of any JSON set as a button, and the following properties will be ordinary text. Please allow me to post a pseudo-code like process.
Loop through all elements of data response
Loop through each key and value of each data element.
If the key is the first occurrence within the data set
display it as a button.
else
display it as ordinary text.
End Inner Loop
End outer loop
What UtsavShah means is that for (key in obj) may iterate keys in obj in any order, JS spec does not enforce any order.
In fact, JS spec does not enforce any order not only for iteration, but also for internal storage: each JS engine implementation (hence depending on browsers) may store your JSON keys in any order, so even though you write your "userId" first, it does not mean at all that the browser will keep it as the first key. For that, you have to use an Array, or use a convention with a specific key.
The way your code is written, it will look for a key named "0" in your object (row). BTW your i iterator is useless in isFirstIndex function.
What you may try to achieve is to test if the value assigned to "userId" key is equal to 0? In that case, you would simply test if (obj["userId"] === 0).
EDIT: (after you have explained that userId is the one to be a button)
If you just want the value in key "userId" to be displayed as a button, you would simply do:
function generateTree(data, selId){
var cnt = "";
for (var i=0; i<5; i++){
var row = data[i];
$.each(row, function (key,value) { // Note that $.each does not necessarily iterates in any specific order either.
if (key === "userId"){
cnt += "<button>" + value + "</button><br/>";
} else{
cnt += "<strong>" + key + "</strong> :" + value + "<br/>";
}
});
cnt += "<br/>";
}
$(selId).html(cnt);
}
EDIT2:
If you want an order, you need an array. If you want ordered keys, you could shape your data like so (of course this must be implemented in both server and client):
[
{"userId": 1},
{"name": "cool name"}
]
If you just need to know which particular key is specific and should be set as a button, make up a convention with your server and have your data specify which is the specific key, e.g.:
{
"userId": 1,
"name": "cool name",
"specificKeyToBeTransformedIntoAButton": "userId"
}

Create JSON string from javascript for loop

I want to create a JSON string from a javascript for loop. This is what I tried to do (which gives me something that looks like a JSON string), but it does not work.
var edited = "";
for(var i=1;i<POST.length-1;i++) {
edited += '"'+POST[i].name+'":"'+POST[i].value+'",';
}
It gives me this:
"type":"empty","name":"email-address","realname":"Email Address","status":"empty","min":"empty","max":"empty","dependson":"empty",
This does not work if I try to convert it into a JSON object later.
Two problems:
You want an object, so the JSON string has to start with { and end with }.
There is a trailing , which may be recognized as invalid.
It's probably better to use a library, but to correct your code:
Change var edited = ""; to var edited = "{"; to start your JSON string with a {
Add edited = edited.slice(0, -1); after the for loop to remove the trailing comma.
Add edited += "}"; after the previous statement to end your JSON string with a }
Your final code would be:
var edited = "{";
for(var i=1;i<POST.length-1;i++) {
edited += '"'+POST[i].name+'":"'+POST[i].value+'",';
}
edited = edited.slice(0, -1);
edited += "}";
Again, it's best to use a library (e.g. JSON.stringify) by making an object with a for loop, adding properties by using POST[i].name as a key and POST[i].value as the value, then using the library to convert the object to JSON.
Also, you are starting with index 1 and ending with index POST.length-2, therefore excluding indices 0 (the first value) and POST.length-1 (the last value). Is that what you really want?
//dummy data
var post=[{name:'name1',value:1},{name:'name2',value:2}];
var json=[];
for(var i=0;i<post.length;i++)
{
var temp={};
temp[post[i].name]=post[i].value;
json.push(temp);
}
var stringJson = JSON.stringify(json);
alert(stringJson );
http://jsfiddle.net/3mYux/
You have extra comma in your JSON string. JSON string format: {"JSON": "Hello, World"}
var edited = "{";
for(var i=1;i<POST.length-1;i++) {
edited += '"'+POST[i].name+'":"'+POST[i].value+'",';
}
// remove last comma:
edited = edited.substring(0, edited.length-1) + "}";
Can't you just build up a hash and do toString on the hash? Something like this:
var edited = {};
for(var i=0;i<POST.length-1;i++) {
edited[POST[i].name] = POST[i].value;
}
Or maybe JSON.stringify is what you are looking for: http://www.json.org/js.html

Categories

Resources