0

How do I turn each item in an array into an individual object?

I'm trying to turn this var myArray = new Array("a", "b", "c"); into this: var a ={name: a, rank: 1} var b ={name: b, rank: 2} var c ={name: c, rank: 3} This is what I tried: var i; var myArray = new Array("a", "b", "c"); for(i = 0; i < myArray.length; i++) { myArray[i] = {name: myArray[i], rank: i} } It didn't work.. I was able to do something similar in python, with myArray = ("a", "b", "c") for item in myArray: item = [item, 1] Can anyone help me out with this? Thank you!

9th Apr 2018, 7:53 PM
Daryl
Daryl - avatar
8 Réponses
+ 6
var i; var myArray = new Array("a", "b", "c"); var output = []; for(i = 0; i < myArray.length; i++) { output.push({name: myArray[i], rank: i}) }
9th Apr 2018, 8:25 PM
John Wells
John Wells - avatar
+ 3
You can reference as: output[1].name
9th Apr 2018, 8:30 PM
John Wells
John Wells - avatar
+ 2
Your Python doesn't do what you want. myArray is still ("a", "b", "c") after your loop. item is changed within the loop, but is gone at the start of the next loop or on exit from the loop. You should instead make a new array or list.
9th Apr 2018, 8:21 PM
John Wells
John Wells - avatar
+ 2
var myArray = new Array("a", "b", "c"); var newArray = myArray.map(function(v,i){ return {name: v, rank: i}; });
10th Apr 2018, 1:00 AM
Calviղ
Calviղ - avatar
+ 2
ES6 js: var myArray = new Array("a", "b", "c"); var newArray = myArray.map((v,i)=>({name: v, rank: i}));
10th Apr 2018, 1:10 AM
Calviղ
Calviղ - avatar
+ 1
John Wells hi thanks for your response. I did in fact create a new list in my python code, but I thought it would be irrelevant here.
9th Apr 2018, 8:23 PM
Daryl
Daryl - avatar
+ 1
Thank you! I'll go try that out!
9th Apr 2018, 8:27 PM
Daryl
Daryl - avatar
0
https://www.w3schools.com/js/js_arrays.asp Another resource the goes deeper into javascript arrays and objects. It should help with your current problem.
9th Apr 2018, 10:16 PM
ODLNT
ODLNT - avatar