0

For my module, I need to declare an unknown sized array of user defined objects with two properties: datatype and FullName. I want to be able to set these properties to null upon creation.

I tried the below code.

var result = [{ dtype:null, fname:null, }];

I get the error: Uncaught TypeError: Cannot set property 'dtype' of undefined.

Any thoughts?

3
  • var foo = []; Commented Feb 6, 2017 at 21:27
  • How can i initialize the properties? Commented Feb 6, 2017 at 21:36
  • 1
    No repro. You're probably not actually using javascript but something else, maybe typescript? Open the javascript console in whatever browser you are in. Paste what you added to your question. Tada. Works. Your error lies in another castle. Commented Feb 6, 2017 at 21:39

2 Answers 2

1

So javascript doesn't support defining or restricting types that go into an array, and you don't have to specify a size either, you can just keep adding those object to it natively

But if you wanted to restrict the types that went into it there is a way

function addThing(thing) {
    if(thing.hasOwnProperty("fullName") && thing.hasOwnProperty("dataType")) {
        array.push(thing);
    }
}

https://jsfiddle.net/9sL920qt/

Sign up to request clarification or add additional context in comments.

Comments

0

Applying Noah s logic, I tried this solution which worked for me.

  var result = [];

Have a temp object:

 var resultItem = {};

set the values of temp object.

resultItem.fname = resultsinJson.Data[i][keys];
 resultItem.dtype =  resultsinJson.Data[i][keys] ;

and then add that object to the final array

 result[i] = resultItem;

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.