3

In my React Native application I am using the RNDBModels package that is a wrapper over AsyncStorage. Currently I am saving a JSON object through RNDBModels and that works correctly, however accessing the data is proving challenging.

When the code is return from the get method, it is return inside a JSON Object and I would essentially like the values from the result, so that I can iterate over it for a list.

The returned result:

 { 
  '1': 
    { 
      name: 'Galaxy', 
      description: '20gram bars', 
      _id: 1 
    },
  '2':
    {
      name: 'Snickers', 
      description: 'Hazelnuts', 
      count: 2, 
      _id: 2 
    }
 }

And the desired outcome so that I can easily iterate over the objects in the array and then render a list in React Native.

[
 { 
    name: 'Galaxy', 
    description: '20gram bars', 
    _id: 1 
 },
 {
    name: 'Snickers', 
    description: 'Hazelnuts', 
    count: 2, 
      _id: 2 
  }
 ]

Any suggestions at accessing the values? I have tried using Object.keys and then subsequently Object.values to no avail sadly.

2 Answers 2

8

You can do it with the in operator :

const data =  { 
  '1': { 
    name: 'Galaxy', 
    description: '20gram bars', 
    _id: 1 
  },
  '2': {
    name: 'Snickers', 
    description: 'Hazelnuts', 
    count: 2, 
    _id: 2 
    }
};

var array = [];

for (let prop in data) {
  array.push(data[prop]);
}

console.log(array);

JSFiddle

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

Comments

1

If you're using lodash just one line of code would work for your purpose

_.values(YOUR_OBJECT);

https://lodash.com/docs#values

It will make an array of values from your object.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.