0

Hello friends I want to create dynamic array of x-y coordinate with help of JSON array value so below JSON value

"data": [
  {
    "x_value": 1,
    "y_value": 1527116400
  },
  {
    "x_value": 43.45,
    "y_value": 1527030000
  },
  {
    "x_value": 43.95,
    "y_value": 1526943600
  },
  {
    "x_value": 43.95,
    "y_value": 1526857200
  },
  {
    "x_value": 44.05,
    "y_value": 1526598000
  },
  {
    "x_value": 44.25,
    "y_value": 1526511600
  },
  {
    "price": 44.1,
    "y_value": 1526425200
  },
  {
    "x_value": 44.3,
    "y_value": 1526338800
  },
  {
    "x_value": 44.25,
    "y_value": 1526252400
  }

]

My Js code as below

var data = null;
var array_data = response.sData.chart_data;
for (let index = 0; index < chart_data.length; index++) {
    data.push({ array_data[index].x_value, y: chart_data[index].y_value });
}

When I run above code I get error message like;

TypeError: null is not an object (evaluating 'data.push')

Any idea how can I solve this? Your all suggestions are appreciable.

2
  • var data =[] :| Commented May 25, 2018 at 10:59
  • You can't use Array.prototype.push() on a boolean variable Commented May 25, 2018 at 10:59

1 Answer 1

1

In your code you can't use Array.prototype.push() on a boolean var data = null; variable..

Better to use Array.prototype.map() that creates a new array with the results of calling a provided function on every element in the calling array.

Code example:

const chart_data = [{"x_value": 1,"y_value": 1527116400},{"x_value": 43.45,"y_value": 1527030000},{"x_value": 43.95,"y_value": 1526943600},{"x_value": 43.95,"y_value": 1526857200},{"x_value": 44.05,"y_value": 1526598000},{"x_value": 44.25,"y_value": 1526511600},{"price": 44.1,"y_value": 1526425200},{"x_value": 44.3,"y_value": 1526338800},{"x_value": 44.25,"y_value": 1526252400}];
const data = chart_data.map(coordinate => ({
  x: coordinate.x_value,
  y: coordinate.y_value
}));

console.log(data);

Sign up to request clarification or add additional context in comments.

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.