EDIT:
I have an array in JS like this: [6.7, 8, 7, 8.6]
and I want this array to look like an array of objects with named properties: [{y: 6.7} , {y: 8}, {y: 7}, {y: 8.6}].
How do I do this in JS
Thanks in advance!
EDIT:
I have an array in JS like this: [6.7, 8, 7, 8.6]
and I want this array to look like an array of objects with named properties: [{y: 6.7} , {y: 8}, {y: 7}, {y: 8.6}].
How do I do this in JS
Thanks in advance!
Incase you want a valid JSON object, try this:
https://jsfiddle.net/6k3wnbs8/1/
var x = [6.7, 8, 7, 8.6];
for(var i in x) {
x[i] = {};
x[i]["y"] = x[i];
}
console.log(x);
If you want it to be exactly same as mentioned in the question [y: 6.7 , y: 8, y: 7, y: 8.6]
, then below will help:
var x = [6.7, 8, 7, 8.6];
for(var i in x) {
x[i] = "y: " + x[i]
}
console.log(x);
you could use map to create an array of objects
[6.7, 8, 7, 8.6].map(function(x) { return {y: x}})
Edit - your other question from the comments of this answer:
var xCoordinates = [1.1, 2.2]
var yCoordinates = [3.3, 4.4]
var result = []
function mapper(key, values) {
for (var i = 0; i < values.length; i++) {
if (result[i] === undefined) {
result[i] = {};
}
result[i][key] = values[i];
}
}
mapper("x", xCoordinates);
mapper("y", yCoordinates);
console.log(JSON.stringify(result));
Use Array#map. Here is the code
var arr = [6.7, 8, 7, 8.6];
function changeArr(num) {
return 'y: '+num ;
};
var newarr= arr.map(changeArr);
console.log(newarr);