Reputation: 6289
I am storing some data in asyncStorage
via @react-native-async-storage/async-storage
in my 'react-native' app. When I pull the data back out I want to assign the results to a drop-menu list, which expects this format:
names = [{name: 'Dave'}, {name: 'Julio'}];
Right now when I pull out the asyncStorage data, and apply JSON.parse()
, it looks like this:
jsonNames: Array [
"{\"name\":\"Chris\"}",
"{\"name\":\"Janet\"}",
"{\"name\":\"Augustine\"}",
]
This is my function to retrieve the data:
getNames = async () => {
try {
const jsonNames = await AsyncStorage.getItem('names')
return jsonNames != null ? JSON.parse(jsonNames) : null;
} catch(e) {
console.log(e);
}
}
Is there a function I can use to clean this up so that it's in the format I need, as described above?
Upvotes: 1
Views: 226
Reputation: 328
It looks like you're storing the data as JSON already and you could change that to avoid a new step parsing the JSON. In any case, if you want to work with the data as is, you could do this:
const jsonNames = [
"{\"name\":\"Chris\"}",
"{\"name\":\"Janet\"}",
"{\"name\":\"Augustine\"}",
];
const names = jsonNames.map(JSON.parse)
Upvotes: 1
Reputation: 3976
to convert it do addition step like this
const jsonNames = [
"{\"name\":\"Chris\"}",
"{\"name\":\"Janet\"}",
"{\"name\":\"Augustine\"}",
];
console.log(jsonNames.map(x => JSON.parse(x)))
also, you can review the way you use to save this value in AsyncStorage
it is look lik you serialize every object on array Separately before saving, not the whole array once.
Upvotes: 1