-1

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!

didi
  • 27
  • 1
  • 8

3 Answers3

1

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);
Anurag Sinha
  • 1,014
  • 10
  • 17
0

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));
bert
  • 466
  • 3
  • 7
  • You mean an array of objects? A single object could only have a single "y" property. – bert Jan 12 '17 at 11:13
  • Aren't you confident with my solution? Should I elaborate? – bert Jan 12 '17 at 11:24
  • I have one more question. If I want to add an additional property to every object how do I do it ? I want the final result to look something like this: [{ x : "A", y : 40 },{ x : "B", y : 30 },{ x : 5, y : 20 } ] for example – didi Jan 12 '17 at 11:29
  • You have 2 arrays? One for the x coordinates and one for the y coordinates? – bert Jan 12 '17 at 11:32
  • I have edited my answer to show one way of handling 2 arrays, there are probably better ways – bert Jan 12 '17 at 11:42
0

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);
Rafique Ahmed
  • 117
  • 2
  • 8