0

I am having an array of String

  var array = ["apple","banana","orange"]

I want trying to convert each of this string to object in this way;

var objectA = new Object(array[0]);

Now when I am checking with

console.log(typeof(a), " ", a) 

It is showing as

object String {0: "a", 1: "p", 2: "p", 3: "l", 4: "e", length: 5} ;

What is my mistake and how can I get apple as an Object? Any help will be appreciated

AVM
  • 592
  • 2
  • 11
  • 25
brk
  • 48,835
  • 10
  • 56
  • 78
  • possible duplicate of http://stackoverflow.com/questions/4215737/convert-array-to-object – AVM Jan 14 '15 at 05:39
  • What are you expecting to happen? – Evan Trimboli Jan 14 '15 at 05:40
  • I expect to come as apple or orange or banana – brk Jan 14 '15 at 05:45
  • 1
    do `.valueOf()`, get the total string as return and then use it wherever you want to use it instead of trying to use it as an object. – Praveen Puglia Jan 14 '15 at 06:13
  • Why are you doing this? I can't think of a single case where you would need to convert a string into an object. A string literal has all the same methods. Doing this can actually create all sorts of strange bugs, as your code shows: `typeof new Object('foo')` returns `'object'`, not `'string'` as one might expect. – Useless Code Jan 14 '15 at 08:19

1 Answers1

0

Whenever you are converting a javascript string to an object, the string is spliced into characters and kept as key value pairs with incremental indexing. But the object also keeps the original string that you can find using valuOf() method. Here's an example,

var array = ["apple","banana","orange"];

var objectA = new Object(array[0]);

console.log(typeof objectA); // object
console.log(objectA.valueOf()); // this will return the PrimitiveValue that in this case is apple

jsFiddle

References : valueOf()

Md Ashaduzzaman
  • 4,032
  • 2
  • 18
  • 34