Getting ' cannot read prop of undefined' for object when applying .replace() - javascript

Im trying to clean up items in an array:
//inside a for loop for items in an array...
var eventsLink = chunk[1];
console.log(eventsLink);
// this works. it returns items like these:
https://examplesite3.com" target="_blank"><b><font>Go</font></b></a>
https://examplesite2.com" target="_blank"><b><font>Go</font></b></a>
https://examplesite1.com" target="_blank"><b><font>Go</font></b></a>
But if I try doing a basic .replace like so, it returns an error:
var eventsLink = chunk[1].replace(/<b>/g,"");
> error: cannot read property replace of undefined
Actual code below. Oddly, eventsDesc does not get this error:
for (var i = 0, length = events.length; i < length; i++) {var chunk = events[i];
chunk = chunk.split("<a href=\"");
var eventsDesc = chunk[0]
.replace(/<\/b>/g,"")
.replace(/<\/span>/g,"")
.replace(/<b>/g,"")
.replace(/<i>/g,"")
.replace(/<\/i>/g,"");
var eventsLink = chunk[1]
.replace(/<font>/g,"")
.replace(/<\/b/g,"");
console.log(eventsLink);
};

Related

Angularjs can't get array length

I am trying to get the array length, when i console log
console.log($scope.community)
I do get a return, but when i try doing the method i found online , like Get the object length in angularjs is undefined
var array = Object.keys($scope.community);
var len = array.length;
console.log(len)
I am returned with 0 and no error
Array call :
var all = displayAll.callAll()
.then(function(response) {
$scope.all = response;
for (var i=0; i< $scope.all.length; i++) {
if ($scope.all[i].CATEGORY == 'Community')
{
$scope.community.push($scope.all[i]);
}
var len = $scope.community.length;
console.log(len);
should return the length of the community.
Plus this method can also be used in Native JS, even without using AngularJS.

Append JSON elements in Ember

I am having an array with some of values (i.e., [1,2,3,4,5]), now i have to convert this array elements into JSON format.
I tries this one,
var Jsondata = {};
for (i = 0; i < Response.get('firstname').length; i++) {
Jsondata.push({
name : Response.get('firstname')[i]
});
}
Ember.Logger.debug(Jsondata );
but it shows some error :
carousel.js:575 Uncaught TypeError: Jsondata.push is not a function(…)
how to append json elements in ember?
Can you please try like this.
var Jsondata = [];
for (i = 0; i < Response.get('firstname').length; i++) {
Jsonvalue = {
name : Response.get('firstname')[i]
}
Jsondata.push(Jsonvalue);
}
Your Jsondata is a hash instead of an array. If you change it to an array your code should work. Your issue is unrelated to Ember

how to get values from json with unknown ammount of given elements

Given this json as example:
[
{"offspring0":"John"},
{"offspring1":"Anna"},
{"offspring2":"Peter"}
]
I can know how many offspring are there with:
offspringCount = (jsonString.match(/offspring/g) || []).length; //jsonString is the json above
This would return 3. Now, how can i get the value of all those offsprings? I have tried:
json = JSON.parse(jsonString);
alert(json[0].offspring[0]);
But this throws Uncaught TypeError: Cannot read property '0' of undefined because offspring is not an array.
I also tried:
alert(json[0]."offspring0");
But getting Uncaught SyntaxError: Unexpected string
My intention is to loop through all the offspring[number] and get the values, was expecting something like this:
for(x=0; x<offspringCount; x++){
alert(json[0].offspring[x]);
}
Note i do not handle the making of the JSON, i only request it to a server.
Try this:
var jsonString = '[{"offspring0":"John"},{"offspring1":"Anna"},{"offspring2":"Peter"}]';
var array = JSON.parse(jsonString);
var offsprings = [];
for (var i=0; i<array.length; ++i) {
for (var key in array[i]) {
if (key.match(/^offspring[0-9]+$/)) {
offsprings.push(array[i][key]);
}
}
}
document.getElementById('output').innerHTML = JSON.stringify(offsprings);
<div id="output"></div>
I thing this code may help you
json = JSON.parse(jsonString);
alert(json[0]['offspring0']);
this means, when you need to loop around your array , you need to do something like this:
for(var index = 0; index < json.length; index++) {
alert(json[index]['offspring' + index]);
}

cannot set property of multidimensional javascript array

My JavaScript code is this:
var i=0;
var ret=[];
ret[i][0]=newID;
ret[i][1]=jobTitle;
ret[i][2]=jobText;
ret[i][3]=jobEmail;
ret[i][4]=jobOrder;
These are all strings and all have value.
I'm getting the error:
"Uncaught TypeError: Cannot set property '0' of undefined" on the
first assignment: ret[i][0]=newID;
Also error at jsfiddle
http://jsfiddle.net/Zf9rE/2/
what am I doing wrong?
You must create ret[i] before you try to add elements to it:
var i=0;
var ret=[];
ret[i] = []; // define ret[i]
ret[i][0]=newID;
ret[i][1]=jobTitle;
ret[i][2]=jobText;
ret[i][3]=jobEmail;
ret[i][4]=jobOrder;
Updated fiddle
Unless there is a reason to hard code the array indexes, you might prefer to either create an array literal (as #Rocket shows in the comments) or use Array.prototype.push():
ret[i].push(newID);
ret[i].push(jobTitle);
Another aproach:
var jobTitle="j title";
var jobText = "j desc";
var jobEmail="jemail";
var jobOrder="j order";
var newID="3";
var i=0;
var ret = new Array();
var matrix = new Array()
ret[0]=newID;
ret[1]=jobTitle;
ret[2]=jobText;
ret[3]=jobEmail;
ret[4]=jobOrder;
matrix[i] = ret;
console.log(matrix[0][0]);
Fiddle: http://jsfiddle.net/robertrozas/Zf9rE/6/

JS code returning error

I'm new to JS and i had to use it for Cloud Code Parse feature. I have a class called "user_picture", through the code i query all the objects and go through it's "City" attribute. i want the response to be an array of unique city names. Anyway, here is the code i'm working on:
Parse.Cloud.define("cities", function(request, response) {
var query = new Parse.Query("user_picture");
query.find({
success: function(results) {
var cities = new Array();
for (var object in results){
var tempArray = [object.get("city")];
if (cities.length > 0){
for (var i = 0; i < cities.length; i++){
if (cities[i].get("city") == object.get("city")) {
break;
} else if (i == cities.length-1) {
cities = cities.concat(tempArray);
}
}
}
}
response.success (cities);
}, error: function() {
response.error("Error");
}
});});
However, when i run this function i receive the following error:
Error: TypeError: Object 0 has no method 'get'
at query.find.success (main.js:15:30)
at Parse.js:2:5786
at r (Parse.js:2:4981)
at Parse.js:2:4531
at Array.forEach (native)
at Object.E.each.E.forEach [as _arrayEach] (Parse.js:1:666)
at n.extend.resolve (Parse.js:2:4482)
at r (Parse.js:2:5117)
at Parse.js:2:4531
at Array.forEach (native) (Code: 141, Version: 1.2.18)
And the response returns null. I tried printing one object from the results array in order to make sure i'm receiving the right query, and it's printing fine the city. What could be the problem?
The for in loop iterates through all the keys of an object literal. Since results is an Array it will iterate through the keys of the Array, which are '0', '1' etc.
This means that the object variable will hold those key vales. And since they are not objects they don't have a method called get.
You need a forEach loop instead.
results.forEach(function(object){
var tempArray = [object.get("city")];
if (cities.length > 0){
for (var i = 0; i < cities.length; i++){
if (cities[i].get("city") == object.get("city")) {
break;
} else if (i == cities.length-1) {
cities = cities.concat(tempArray);
}
}
}
}
});
Or if you're targeting ES3 then you should use a for loop
for(var i = 0, length = results.length; i< length; i++){
var object = results[i];
var tempArray = [object.get("city")];
if (cities.length > 0){
for (var i = 0; i < cities.length; i++){
if (cities[i].get("city") == object.get("city")) {
break;
} else if (i == cities.length-1) {
cities = cities.concat(tempArray);
}
}
}
}
I recall working with Parse objects a bit and there seemed to be times to access them as an object (by direct parameter access) and sometimes by using the get method and it looks like you're mixing up the array access and object (from Parse) access methods.
Also, your list generator doesn't seem like it's really building a unique list. You only check to see if the current city is the same as the city you're going to add.
I might do something more like this (for the success method):
function(parseResults) {
var cities = {};
var ii=0;
var nResults = parseResults.length
for(;ii<nResults;++ii) {
cities[result.get('city')] = 1
}
var citiesArray = cities.keys();
response.success(citiesArray);
}
What we do here is build up an object whose keys are city names. Then return the keys as an array. What this does for us is automatically build a unique list because object keys should be unique.
If the result.get gives you problems, try replacing it with result.city. But i suspect the error you were seeing with your first example was trying to call get on the Array element.

Categories

Resources