1

I am curious if it is possible to check if the object value exists and if it exists I want to check if it is a string or an array.

// var n is a dynamic variable that is retrieved from $(this)
var d = {};
if(typeof(d[n]) == "undefined"){
   d[n] = "value";

}else{
   if(typeof(d[n]) == "string"){
     //Convert string to array using its curent value plus an additional value

   }else{
     //Append value to array

   }
}

Currently I am using a loop to create an object for AJAX. I have a few of the same names for the data points similar to an input with the name="name[]".

How can I accomplish this?

4
  • typeof needs no parenthesis. Commented Dec 20, 2016 at 18:20
  • What is not working? Or are you asking for the comments to be written in code? Commented Dec 20, 2016 at 18:20
  • 1
    d[n] = [d[n], "additional value"]? You should provide inputs and expected outputs if you want a real answer. Also, you know jQuery has $.serializeArray(), right? Commented Dec 20, 2016 at 18:20
  • d[n] = [].concat(d[n],v) sames results if v is string or array Commented Dec 20, 2016 at 18:29

1 Answer 1

3

All you need to do is reassign the property to an array if a string (d[n] = [d[n], newValue]), or call Array#push if it's not.

var newValue = "testing123";

var d = {};
if(typeof d[n] == "undefined"){
    d[n] = "value";

}else{
    if(typeof d[n] == "string"){
        //Convert string to array using its current value plus an additional value
        d[n] = [d[n], newValue];
    }else{
        //Append value to array
        d[n].push(newValue);
    }
}
Sign up to request clarification or add additional context in comments.

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.