0

I am working for the first time on a project with JSON but I need to get al timestamps form the JSON file to put it in a array in a chart that al the timestamps are displaying on the chart.

JSON file look like this:

    [
      {
        timestamp: "1541404800",
        data: {
          OK: {
            count: "8",
            percentage: "100"
      },
          NOK: {
            count: 0,
            percentage: 0
        }
      }
    },
      {
        timestamp: "1541408400",
        data: {
          OK: {
            count: "1",
            percentage: "100"
      },
          NOK: {
            count: 0,
            percentage: 0
        }
      }
    }
  ]
str
  • 42,689
  • 17
  • 109
  • 127
J. Kelks
  • 30
  • 3
  • 1
    Please read [What is the difference between JSON and Object Literal Notation?](https://stackoverflow.com/questions/2904131/what-is-the-difference-between-json-and-object-literal-notation) – str Nov 06 '18 at 08:28
  • 1
    The example is not JSON. – Teemu Nov 06 '18 at 08:33

2 Answers2

2

what you are looking for is the function map. See documentation for more details.

for example:

var data = [
  {
    timestamp: '1541404800',
    data: {
      OK: {
        count: '8',
        percentage: '100'
      },
      NOK: {
        count: 0,
        percentage: 0
      }
    }
  },
  {
    timestamp: '1541408400',
    data: {
      OK: {
        count: '1',
        percentage: '100'
      },
      NOK: {
        count: 0,
        percentage: 0
      }
    }
  }
];
var timestamps = data.map(function(d) { return d.timestamp }));
Patrick
  • 51
  • 4
0

Just use for to iterate over the array to get the data

var json = [
  {
    timestamp: '1541404800',
    data: {
      OK: {
        count: '8',
        percentage: '100'
      },
      NOK: {
        count: 0,
        percentage: 0
      }
    }
  },
  {
    timestamp: '1541408400',
    data: {
      OK: {
        count: '1',
        percentage: '100'
      },
      NOK: {
        count: 0,
        percentage: 0
      }
    }
  }
];
var newArr = [];
for (var i = 0; i < json.length; i++) {
  newArr.push(json[i].timestamp);
}
console.log(newArr); // ['1541404800','1541408400']
Jeremy Su
  • 781
  • 1
  • 6
  • 12