I'm making a program that searches through an object and prints the properties of that object to the console. The program compiles and runs, but the only thing that prints to the console is undefined. How do I fix this?
function printInfo(array) {
var usersLength = array.length;
for (var i = 0; i < usersLength; i++) {
console.log("Name: ", array.name, "Role: ", array.role);
return array.name, array.role;
}
}
This function would be passed an object with certain properties inside ( name, role, dob). The expected result is that these values would print. But what actually prints is "undefined".
Bobby
this will return undefined and an error on your console:
return array.name, array.role;
array.name property does not exist try this so you know what value function parameter has
console.log(array)
more about arrays look on this site https://www.w3schools.com/js/js_arrays.asp
If you had ES6, then use:
const printInfo = array => {
for(let info in array){
console.log(info);
}
}
Related
I have this function that accepts an array of objects as input and transforms it into an array of strings, but when I do the console log the property are wrong, I can't understand why.
as you can see the two console logs are of the same object, in the first the x.credititoTotale property has a value in the second console.log where I go to access it directly with x.credititoTotale has another value
const stringArray = [];
export const convertToStringForDb = (objectArray) => {
objectArray.forEach((x) => {
console.log(x);
console.log(x.credititoTotale + " " + x.id);
stringArray.push(
`${x.id}/${x.cognome}/${x.nome}/${x.totaleCG}/${x.time}/${x.credititoTotale}`
);
});
return stringArray;
};
look the screen ---> screen of console.log
when I print x the value of 'credititoTotale' is '-20'
when I print x.credititoTotale the value is '-10'
it should always be the same because it is the same object printed in the same for loop
I am basically trying to get this problem to work and have isolated the issue to line 21. I think the way I'm trying to access the object key is wrong. I am simply trying to say: if the object key in the new object exists in the original array, push the new value from the new object into the new array.
Edit to add code block
function valueReplace(array, obj) {
var replaced = [];
for (var i = 0; i < array.length; i += 1) {
var value = obj[array[i]];
if (array.indexOf(obj.i) !== -1) {
replaced.push(value);
} else {
replaced.push(array[i]);
}
}
return replaced;
}
You have a mixed up error report, but at the actual code, you try to access the object with the property i, obj.i, which not exists. Read more about property accessor.
For getting the wanted result, you might use the in operator for checking if a property in an object exists.
if (array[i] in obj) {
replaced.push(obj[array[i]]);
} else {
replaced.push(array[i]);
}
It looks like one of the issues you are having is trying to access a dynamic property with dot notation, which JS generally doesn't like. I reversed your logical if because IMO it makes more sense to see if the object has a property than get a property and then get the index of the array, but you could reverse it back to using index of by array.indexOf(obj[i]) !== -1
function valueReplace(array, obj) {
let replaced = [];
for (let i = 0, len = array.length; i < len; i++) {
if (obj.hasOwnProperty(array[i])) {
replaced.push(obj[array[i]]);
} else {
replaced.push(array[i]);
}
}
return replaced;
}
Because I generally like simplifying things here is this functionality rewritten in ES6 compatible code, using array.prototype.map. Don't use it for your homework, but if you want you can work it backwards into a standard function ;).
const valueReplace = (array, obj) => array.map(val => (obj.hasOwnProperty(val)) ? obj[val] : val);
Let´s assume I have an object property which is passed into a function. In this case 'name' is filled with 'myObject.name' (which has the value 'Tom') - so basically 'Tom' gets passed into the function as the 'name'
function(name) {
do something //non-essential for my question
}
Is it possible to get the object, where 'Tom' is the property of, just by having the information 'Tom'? Basically I´m looking to get myObject.
Thanks :)
No, that's not possible.
All that the function knows is that one of its parameters was pointed to the string "Tom", not what else points to that string somewhere else in memory.
You can store objects within an array, filter the array to match property name of object to parameter passed to function using for..of loop, Object.entries(), which returns an array of property, values of an object.
const data = Array();
const setObjectPropertyName = _name => {
data.push({[_name]:_name});
return data
}
const getObjectByPropertyName = prop => {
let res = `${prop} property not found in data`;
for (let obj of data) {
for (let [key] of Object.entries(obj)) {
if(key === prop) return obj;
}
}
return res;
}
let s = setObjectPropertyName("Tom");
let g = getObjectByPropertyName("Tom");
let not = getObjectByPropertyName("Tome");
console.log(s,"\n", g, "\n", not);
Disclaimer: you absolutely should not do this. I'm only posting this because it is in fact possible (with some caveats), just really not advisable.
Going on the assumption that this is running in the browser and it's all running in the global scope (like in a script tag), you could technically iterate over the window object, check any objects in window for a name property and determine if their name property matches the name passed to your function.
var myObject = {
name: 'Tom',
thisIs: 'so awful',
imSorry: true,
};
function doSomethingWithName(name) {
for (var obj in window) {
var tmp = window[obj];
if (Object(tmp) === tmp && tmp.name === name) {
return tmp;
}
}
}
console.log(doSomethingWithName(myObject.name));
I was using array like this
var names=['a','b','c'];
when I tried to access names[5]. it returns undefined simply,gives no error.
After that I changed my array like this
var names=[];
for(var i=0;i<inputNumberByUser;i++) //guys my array is populating dynamically,depends upon user input
{
names.push({FirstName:'abc',LastName:'zyx'});
}
When I tried below code, it gives me error that, Could not read FirstName of undefined
names[5].FirstName;
why above line is giving error? it should just return undefined as normal array
names[5] and names[5].FirstName both are not defined. names[5] returns 'undefined' but names[5].FirstName error. thats my point. names[5].FirstName should also simply return 'undefined' as names[5] did
Why you are getting error?
Here names[5] returns undefined and you are trying to access FirstName property of undefined element. It's like trying to get address of someone who doesn't exists.
And You also have error in line for(var i=i<3;i++) may be you wanted to write for(var i=0; i<3; i++)
Possible Solution
If you are looking to push to names array then you should do something like below:
var names=[];
// Push objects to names
for (var i = 0; i < 3; i+=1) {
names[i] = {
firstName: 'Name: ' + i
}
// Lastname defined only for 2 index object
if (i === 2) {
names[i].lastName = 'Lastname only on 2';
}
}
for (var i = 0; i < 3; i+=1) {
// outputs names[i]
console.log(names[i]);
// Check whether lastName property exists on the element or not
if (!names[i].hasOwnProperty('lastName')) {
console.log('no lastName property defined');
}
}
Here we are creating object and assigning to names[i]. Remember, i is incrementing so each time we'll be assigning objects to new position.
Then in second loop, I am just referencing to those previously assigned values and checking whether they have lastName property defined on them or not.
If you are still confused let us know and we'll try to help you.
Because your for iteration does not reach the sixth (counting zero) index, but only the third.
What you are doing inside the for (var i = 0; i < 3; i++) is essentially:
names.push({FirstName:'abc',LastName:'zyx'});
names.push({FirstName:'abc',LastName:'zyx'});
names.push({FirstName:'abc',LastName:'zyx'});
The result of the iteration would be this:
console.log(names[0].FirstName); // "abc"
console.log(names[1].FirstName); // "abc"
console.log(names[2].FirstName); // "abc"
console.log(names[3].FirstName); // undefined
console.log(names[4].FirstName); // undefined
console.log(names[5].FirstName); // undefined
By doing console.log(names[5]) you are outputting the fifth index's content of the names variable. undefined in javascript is not necessarily an error message.
names[5]
^^^ undefined
By doing console.log(names[5].FirstName) instead, you are trying to access a property of an object that does not exist, since names[5] is undefined.
names[5].FirstName
^^^ undefined
Your array has three elements. Your trying to access the sixth element which in your above code will not exist.
For the first part of your question, you have created an array having 3 elements i.e var names=['a','b','c']; and you are trying to access 6th element from your defined array names[5], which not really exist. Hence it's returning undefined.
For the second part of your question you have following codes:
var names=[];
for(var i=0;i<3;i++)
{
names.push({FirstName:'abc',LastName:'zyx'});
}
So above piece of codes create names array having 3 element and each one is an object. So you have to access it like names[0].FirstName. But you are trying to access names[5].FirstName, where 6th elements in names array is not really exist.
Hope this will help you!
Im trying to get a sum of array injected into a function that loops until all the values are added, the console.log right before the "return" logs the right value, meaning the code works, but when I try to use that function with any array it returns "undefined"...
var total = function(arr) {
console.log(arr);
if(arr.length > 1) {
var temp = []
for(var i=0, len=arr.length-1; i<len; i++) {
temp.push(arr[i] + arr[i+1]);
}
total(temp);
}
else {
console.log(arr.join()); // 48, exectly what I need
return parseInt(arr.join());
}
}
var sup = total([1,2,3,4,5]); // undefined
Not completely sure how to debug it..
If your arr.length is greater than one, you will invoke total with the temporary array, however, you don't do anything with this temporary array - you don't return it, or utilize it in any way, so the intermediate results are lost.
In addition - this is not a self invoking function; it is recursion.