Replace one string with another using Angular.js or JavaScript [duplicate] - javascript

This question already has answers here:
Rename the property names and change the values of multiple objects
(3 answers)
Closed 7 years ago.
I have some JSON data and I need to replace one value with another string using Angular.js or JavaScript. My code is below:
$http({
method:'POST',
url:"php/getFilterCodeData.php",
data:filterData,
headers: { 'Content-Type': 'application/x-www-form-urlencoded' }
}).then(function successCallback(response){
console.log('filter',response.data);
$scope.last=[];
for(var i=0;i<response.data.length;i++){
$scope.arrCode=response.data[i].generated_code.split(',');
}
//console.log('arr',$scope.arrCode);
for(var i=0;i<$scope.arrCode.length;i++){
$scope.last.push($scope.arrCode[i].split("_").pop());
}
//console.log('last',$scope.last);
var newStr=$scope.last[0]+"-"+$scope.last[$scope.last.length-1];
//console.log('new str',newStr);
},function errorCallback(response) {
})
Here I am getting the below data using console:
filter [{
customer_name: "Big-Bazar"
expired_date: "23-12-2015"
generated_code: "medilink_global_01,medilink_global_02,medilink_global_03,medilink_global_04,medilink_global_05,medilink_global_06,medilink_global_07,medilink_global_08,medilink_global_09,medilink_global_10,medilink_global_11,medilink_global_12,medilink_global_13,medilink_global_14,medilink_global_15,medilink_global_16,medilink_global_17,medilink_global_18,medilink_global_19,medilink_global_20,medilink_global_21,medilink_global_22,medilink_global_23,medilink_global_24,medilink_global_25,medilink_global_26,medilink_global_27,medilink_global_28,medilink_global_29,medilink_global_30,medilink_global_31,medilink_global_32,medilink_global_33,medilink_global_34,medilink_global_35,medilink_global_36,medilink_global_37,medilink_global_38,medilink_global_39,medilink_global_40"
no_of_voucher: "40"
status: "generated"
voucher_amount: "3000"
voucher_code_id: "13"}]
Here I need to replace the generated_code: value with newStr. The expected output should be:
generated_code:01-40

In the Javascript:
$scope.filter = filter;
$scope.filter[0].generate_code = newStr;
To show the string, just use {{ filter[0].generate_code }} in your template.
AngularJS always watches changes to variables in the scope and will replace them in the template as they change, so it's pretty straight forward.

you do it like this:
response.data[i].generated_code=newStr;

Related

How to get D3 csv data into a different variable [duplicate]

This question already has answers here:
How do I return the response from an asynchronous call?
(41 answers)
Closed 4 years ago.
I am trying to extract imdb data from a csv and put two elements of it into an array of objects. There are 10 fields. I only want to use 2 in my chart. I am trying this:
var mydata;
// Grab the data
d3.csv('./movies.csv', function(csv){
csv.forEach(function(d){
mydata += {rating: d.imdbRating,
winsNoms: d.WinsNoms };
});
});
console.log(mydata);
Can somebody explain exactly what is going on here and why I get undefined when I try to output mydata in the final line? Finally, how do I change it around so it works?
You should push objects into an array. See adjustments below:
var mydata = [];
// Grab the data
d3.csv('./movies.csv', function(csv){
csv.forEach(function(d){
mydata.push({
rating: d.imdbRating,
winsNoms: d.WinsNoms
});
});
});
console.log(mydata);
You’ll need to first declare an empty array. Then you can push items into it.
To only use part of the set, you can use “slice” to truncate the array.
var mydata = [];
// Grab the data
d3.csv('./movies.csv', function(csv){
csv.forEach(function(d){
mydata.push({rating: d.imdbRating,
winsNoms: d.WinsNoms });
});
});
console.log(mydata);

Read a JSON list in list [duplicate]

This question already has answers here:
How can I access and process nested objects, arrays, or JSON?
(31 answers)
Closed 6 years ago.
I have a json like this :
{
"Project
[id=1, dateDebut=2017-01-13, dateFin=2017-01-18, description=qsd, sponsor=qsd ]"
:
[
{"id":1,"title":"qsd ","description":"qsdqsd","dateFin":"2017-01-26"},
{"id":2,"title":"sss ","description":"sss","dateFin":"2017-01-26"}
]
}
originated from : return new ObjectMapper.write(Map<Project,List<Task>> projectTasks = new LinkedMultiValueMap<>()) ;
EDIT : this is the real response :
{"Project [id=1, name=qsdsqd, type=null, done=false, dateDebut=2017-01-13, dateFin=2017-01-18, description=qsd, sponsor=qsd, client=qsd, showable=true]":
[{"id":1,"title":"qsd ","description":"qsdqsd","dateFin":"2017-01-26","dateDebut":"2017-01-14","period":null,"done":false,"status":"Actif","priority":"Normal"},
{"id":2,"title":"task 2 ","description":"qsdqsd","dateFin":"2017-01-26","dateDebut":"2017-01-14","period":null,"done":false,"status":"Actif","priority":"Normal"}]}
How can I read the list of tasks in the client side ?
First of all, your JSON is not valid. Are you sure that is a line break between the word Project and [id...]. A valid JSON would be:
{
"Project [id=1, dateDebut=2017-01-13, dateFin=2017-01-18, description=qsd, sponsor=qsd, ]":
[
{"id":1,"title":"qsd ","description":"qsdqsd","dateFin":"2017-01-26"},
{"id":2,"title":"sss ","description":"sss","dateFin":"2017-01-26"}
]
}
You can have object key names like that. But i'ts not very friendly to retrieve data.
If you cannot change your data schema (or just don't want), you can iterate over the Object with the
Object.keys(obj).forEach ( (key) => {
console.log('key: ' + key);
console.log('value: ' + obj[key]);
/* you can iterate over your value (tasks) here */
obj[key].forEach( (task) => {
console.log('task1: ', task);
});
}); //where obj is your json
Or you can access the first object property with:
obj[Object.keys(obj)[0]]; //where obj is your json
EDIT As pointed by #André Dion, forEachis best suited to iteration, not map. And we're assuming your response is already parsed from the server (by yourself or by a lib like jquery). If not, you should do a JSON.parse(response); to retrieve the object.
You may try this:
Assume above response in stored in var response.
for(var project in response) { // this will get every project
for(var i=0; i<project.length; i++) { // this will iterate over the array for each project which are your tasks.
console.log("task" + project[i]);
console.log(project[i]["id"]); // access each tasks id, similar for other attributes
}
}

reading json string in javascript [duplicate]

This question already has answers here:
How can I access and process nested objects, arrays, or JSON?
(31 answers)
Closed 8 years ago.
I am trying to read a json string which looks like this.
"student":{
"0":[{
"name":"manet",
"marks":114
}],
"1":null,
"2":null,
"3":null,
"4":null,
"5":null,
"6":null,
"7":null,
"8":null,
"9":null,
"10":null,
"18":[{
"name":"Om",
"marks":75
}]
}
I am trying to read something like this
console.log("JSON Marks ", json[0].marks) or
console.log("JSON Marks #1", json[0][0].marks)
I just put jso[0] "0" is index i just put hardcoded to test
but none of the above is working
assuming that your code is saved in a variable called json then json.student[0][0].marks
You need this : http://jsbin.com/qazex/2/edit
console.log("JSON Marks ", json["student"][0][0].marks)
var json={"student":{
"0":[{
"name":"manet",
"marks":114
}],
"1":null,
"2":null,
"3":null,
"4":null,
"5":null,
"6":null,
"7":null,
"8":null,
"9":null,
"10":null,
"18":[{
"name":"Om",
"marks":75
}]
}};
console.log("JSON Marks ", json["student"][0][0].marks)
Try this way to access to object
var json = {"student":{
"0":[{
"name":"manet",
"marks":114
}],
"1":null,
"2":null,
"3":null,
"4":null,
"5":null,
"6":null,
"7":null,
"8":null,
"9":null,
"10":null,
"18":[{
"name":"Om",
"marks":75
}]
}
}
alert("JSON Marks "+ json["student"]["0"]["0"]["marks"]) ;
JSFIDDLE

javascript strange comparison of strings [duplicate]

This question already has answers here:
Which equals operator (== vs ===) should be used in JavaScript comparisons?
(48 answers)
Difference between == and === in JavaScript [duplicate]
(2 answers)
Closed 8 years ago.
I have an ajax function that sends an email to somewhere and receives a response from the server from a json object with type = either success or error
$("#submit_btn").click(function(event) {
event.preventDefault();
var post_data = {
'email': $("#email").val()
};
$.post( "sendEmail.php", post_data ).done(function(response){
if(response.type == 'success'){
$("#sentmail").fadeIn("slow")
setTimeout(function(){
$("#mail").val("Enter your email here");
$("#sentmail").fadeOut("slow")
},3000);
}
else{
$("#sentmailfail").fadeIn("slow")
setTimeout(function(){
$("#mail").val("Enter your email here");
$("#sentmailfail").fadeOut("slow")
},3000);
}
},"json")
});
The interesting part is that if I console.log(response) I get for instance {"type":"success","desc":"something"} and then straight after that console.log( (response.type == "error") ) // TRUE
if I take the consoled log from response and assign it to a variable for instance a = {"type":"success","desc":"something"} then a.type == "error" is false.
Can someone explain this?
If the output of console.log(response) is
{"type":"success","desc":"something"}
then response is most likely still a string (containing JSON), and strings don't have a type property:
> "foo".type == "error" // `undefined` is never equal to a string
false
Objects usually look differently in the console:
> console.log({"type":"success","desc":"something"})
Object {type: "success", desc: "something"} // in Chrome and Firefox at least
Solution: Parse the string first:
response = JSON.parse(response);
Related to jQuery:
I noticed that you intend to let jQuery parse the JSON for you, but you are passing "json" to the wrong function. You have to pass it to $.post(...), not to .done(...):
$.post("sendEmail.php", post_data, "json").done(...);
// instead of
// $.post("sendEmail.php", post_data).done(..., "json");
Then you don't need to parse it manually.
Related: Parse JSON in JavaScript?

How do I access CSV data using d3.js [duplicate]

This question already has answers here:
How can I access and process nested objects, arrays, or JSON?
(31 answers)
Closed 9 years ago.
I have entered the following code in the Chrome console:
d3.csv("dataset32.txt")
.row(function(d) { return {time: +d.time, value: +d.val}; })
.get(function(error, rows) { console.log(rows); });
This returns an array of 160 objects which has the data of my CSV file.
How do I reference the data in these objects?
The "dataset32.txt" is CSV data which looks like this:
time,val
0,1.8988762857143
0.0625,0
0.125,-2.6204492857143
0.1875,-0.34179771428571
The console prints out the result of the above commands as follows:
[Object, Object, Object…]
[0 … 99]
0: Object
time: 0
value: 1.8988762857143
__proto__: Object
So how do I reference the data inside these objects: "time" and "value"?
Here's a straight forward method for importing your csv file using d3.
d3.csv("path to the csv", function(data, error) { }).
More info about csv.
Here's a function that's help you.
Step 1 : Importing your CSV file.
d3.csv("path to your csv file", function(data, error) {
// You're function goes in here.
})
Step 2 : Targeting your data.
// This can be done using the data variable assigned in the function.
data.forEach(function(d) {
// Function goes in here.
})
Step 3 : Targeting your columns.
// Suppose you have 2 columns namely time and val.
data.forEach(function(d) {
// You can target your columns using this fucntion.
// function(d) {return d.colname}
// Here I'm parsing your time and val col numbers to actual numbers after importing.
d.time = +d.time;
d.val = +d.val;
})
Documentation for d3.
Hope this helps.

Categories

Resources