-4

I need to change an array into an object using javascript

For an example. I have an array which looks like :

colours [        
["black","red",shades : ["0","1","2"]]        
]

I want to change this to :

colours [
    {
    "black","red", shades : ["0","1","2"]
    }
]

Can anyone please tell me how I can do this using javascript code.

qualitytest
  • 763
  • 1
  • 10
  • 18
  • ["black","red",shades:["0","1","2"]] this is not a valid array. arrays dont have defined keys in js, only object – VMcreator Aug 07 '15 at 02:19
  • 1
    Neither the object is a valid one ... – Willian Aug 07 '15 at 02:20
  • 1
    Check out [what an object looks like](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object) and [what an array looks like](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array?redirectlocale=en-US&redirectslug=JavaScript%2FReference%2FGlobal_Objects%2FArray), and tell us why you want to do this. – iplus26 Aug 07 '15 at 02:27
  • i am sorry for the confusion. I am a beginner. What i want to do it to make JSON object. colours [ { "black","red", shades : ["0","1","2"] } ] will that be correct? – qualitytest Aug 07 '15 at 02:29
  • @qualitytest That's not correct. Check out the links above. – iplus26 Aug 07 '15 at 02:31
  • No, I'm afraid that will not be correct. You need to post what you actually have. You don't have the things you posted because they cannot exist. – david Aug 07 '15 at 02:32
  • I am afraid it is difficult to share entire code. I can show the browser debug content. what i have currently is this 0: Array[0] prop1: Object prop2: Array[40] descriptor: Array[0] prop3: Array[10] prop4: Array[1] __proto__: Array[0] length: 1 __proto__: Array[0] what i want to change to is this 0: Object prop1: Object prop2: Array[40] descriptor: Array[0] prop3: Array[10] prop4: Array[1] __proto__: Array[0] length: 1 __proto__: Array[0] – qualitytest Aug 07 '15 at 02:40
  • Why don't express your object as `{colors: ["black","red"], shades:["0","1","2"]}` ? Your sample object notation doesn't make sense at all. – TaoPR Aug 07 '15 at 03:24

2 Answers2

1
var arr = $.map(obj, function(el) { return el; });

Fiddle

This question is been asked.

Here's the full details

Community
  • 1
  • 1
aldrin27
  • 3,407
  • 3
  • 29
  • 43
  • This answers how to convert an object to array. I want to do it the other way round. I want to convert an array to object. Can you please help – qualitytest Aug 07 '15 at 02:30
1
function toObject(arr) {
 var rv = {};
 for (var i = 0; i < arr.length; ++i)
  rv[i] = arr[i];
 return rv;
}

Try to read this

Community
  • 1
  • 1
aldrin27
  • 3,407
  • 3
  • 29
  • 43