gbland777
gbland777

Reputation: 725

React Native javascript object value to array

What I am trying to accomplish.

Hydrate chart data with my data from firebase

Issue

The chart I am using want's data in this format

data: [
    { value: 15 },
    { value: 10 },
    { value: 12 },
    { value: 11 },
  ]

I have the this.datasource that populates my listview and then I can get the values I want in the chart, just the wrong format. I don't know how to get the data without the quotes.

var chartArrayFilter = (JSON.stringify(items, ['value']));

console.log = [{"value":"5"},{"value":"9"},{"value":"0"},{"value":"4"}]

My Question

I have tried to hack that array (or string) and remove the double quotes, but I don't thing React Native lets that happen. Am I doing this completely wrong? How do I get the data I want in that format from a javascript object?

This is the package I am working with https://www.npmjs.com/package/react-native-charts

Thanks!

Upvotes: 1

Views: 10239

Answers (1)

IGNIS
IGNIS

Reputation: 440

If you don't need to stringify:

It looks to me like you're using JSON.stringify as a way to remove unnecessary properties from an array of objects. For example, assuming your items array looks something like this:

items = [
  {
    value: 5,
    foo: 'bar'
  },
  {
    value: 9,
    bar: 'baz'
  }
];

then calling JSON.stringify on that will give you "[{"value":5},{"value":9}]" (notice how everything is, well, stringified).

Perhaps a better approach would be the following:

var chartArrayFilter = items.map(function(item) {
  return {value: item.value};
});

which will give you [{value: 5}, {value: 6}]. Notice nothing is stringified in that structure; it's just an array of objects.

If you DO need to stringify:

If, for whatever reason, you do need to call JSON.stringify on your items array to pick the properties you want, you can simply reverse it with

JSON.parse(items)

after you call JSON.stringify. This will give you [{value: 5}, {value: 6}, ...], same as above.

Conclusion

Once you've prepared your items array in one of the two ways mentioned above, you should be able to painlessly pass it into react-native-charts!

Upvotes: 2

Related Questions