1

I have the following array:

dataSeries.data=[10,20,40,40,20];

However I would like to get each array element in JavaScript object

myjs=[{data:10},{data:20},{data:40},{data:40},{data:20}];

I have tried the following but does not work:

for (i = 0; i < self.dataSeries.length; i++) {
    self.dataSeriess[i].data = self.dataSeriess[i].data.map(function (x) {
        return { data: x };
    });
}
1
  • What is the actual problem you are trying to solve? Commented May 22, 2015 at 2:17

4 Answers 4

2

You can just loop through dataSeries.data and append objects to myjs (jsFiddle demo):

dataSeries.data = [10,20,40,40,20];
var myjs = [];
for(var i = 0; i < dataSeries.data.length; i++) {
    myjs.push({ data: dataSeries.data[i] });
}

Or, if you want to use Array.prototype.map, then you don't even need a loop (jsFiddle demo):

dataSeries.data = [10,20,40,40,20];
var myjs = dataSeries.data.map(function(x) {
    return { data: x };
});
Sign up to request clarification or add additional context in comments.

Comments

1

You've over complicated your loops.

Here's a simple .map() example.

http://jsbin.com/waxohezozu/1/edit?js,console

var data = [10,20,40,40,20];

data = data.map(function (e) {
  return {
    data: e
  };
});

console.log(data);

Comments

1
var myjs = dataSeries.data.map(function(x){
  return {data: x};
});

Comments

0

You could use :

function toObject(arr) {
   var result = {};
   for (var i = 0; i < arr.length; ++i)
      result.push({data :arr[i] });
   return result;
}

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.