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!
8 Antworten
+ 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})
}
+ 3
You can reference as: output[1].name
+ 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.
+ 2
var myArray = new Array("a", "b", "c");
var newArray = myArray.map(function(v,i){
return {name: v, rank: i};
});
+ 2
ES6 js:
var myArray = new Array("a", "b", "c");
var newArray = myArray.map((v,i)=>({name: v, rank: i}));
+ 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.
+ 1
Thank you! I'll go try that out!
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.