简体   繁体   中英

How to convert JSON object into an array in React Native

I am getting a JSON object from Firebase. I am trying to convert it into an array of objects.

I can solve this by getting childs from Firebase one-by-one and add them into array however, that is not a good practice for my case.

The format of JSON object is as following:

key: {
      id1: {some stuff here},
      id2: {some other stuff},
    ...
}

Now what I want to get from this JSON object is :

arrayName: [
         {id1:{some stuff here},
         id2:{some other stuff}
]

Hope my description if fully understandable. Any help would be appreciated

This is just plain javascript, it has nothing to do with react native. By the way, you can use Object.keys to get an array with all the keys, then map the strings as objects:

 const x = {foo: 11, bar: 42}; const result = Object.keys(x).map(key => ({[key]: x[key]})); console.log(result); 

This code worked for me.

const JSONString = res.data;
      object = JSON.parse(JSONString);
      array = Object.keys(object).map(function(k) {
        return object[k];
      });

Where res.data is the response I am getting from an api

Using Object.entries , you can avoid the extra hash lookup on every item.

 const x = { foo: 11, bar: 42 }; const result = Object.entries(x).map(([key, val]) => ({ [key]: val })); console.log(result); 

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM