CodeNewbie Community 🌱

Discussion on: Alter multiple objects at once

Collapse
 
shaikmdmusayyeb profile image
Shaik • Edited

Hey Daniel Uber , Thanks for your quick response

Here is what I'm getting in response of your suggested code,
community.codenewbie.org/remoteima...

  objects.forEach(function (object) {
          ^

TypeError: objects.forEach is not a function
    at alterObjects (/usercode/index.js:5:13)
    at executeTests (/usercode/index.js:85:3)
    at main (/usercode/index.js:95:13)
    at Object.<anonymous> (/usercode/index.js:115:1)
    at Module._compile (internal/modules/cjs/loader.js:778:30)
    at loader (/usr/local/lib/node_modules/babel-register/lib/node.js:144:5)
    at Object.require.extensions.(anonymous function) [as .js] (/usr/local/lib/node_modules/babel-register/lib/node.js:154:7)
    at Module.load (internal/modules/cjs/loader.js:653:32)
    at tryModuleLoad (internal/modules/cjs/loader.js:593:12)
    at Function.Module._load (internal/modules/cjs/loader.js:585:3)```



 although I'm a beginner I was trying hardly to solve this
Enter fullscreen mode Exit fullscreen mode
Collapse
 
djuber profile image
Daniel Uber

Hi Shaik,

Well, that error message is more information than we had before - what it says is that the result returned from constructor is not an array (and might just be a normal object like {}). This is something we can tell, because forEach is a method present on arrays, but the variable objects didn't have that function present when it was called. It also says the code you wrote in the function is getting called (the error happened inside your function).

You could try to see if you always get just a single object back, by doing something like this:


alterObjects = function(constructor, greeting) {
  // assuming constructor returns an object
  object = constructor();

  // add greeting attribute
  object.greeting = greeting;

 // and return it
  return object;
}
Enter fullscreen mode Exit fullscreen mode

If that's still failing - it looks from the screenshot like you have a "show console" tab available in addition to the Results - you might try to get a look at the constructor()'s output by trying this and checking that tab afterward to get a look at what you're trying to modify:


alterObjects = function(constructor, greeting) {
  // assuming constructor returns an object
  object = constructor();

  // take a peek at what we get, display on the console
  console.log(object);

  // add greeting attribute
  object.greeting = greeting;

 // and return it
  return object;
}
Enter fullscreen mode Exit fullscreen mode

It's possible that sometimes you get an array and sometimes you get a plain object, in which case the solution might have to check whether forEach is a function and decide what to do. It's also possible that I don't know any more than you about the problem, and the right answer might be "obvious" to someone who knew javascript better.