简体   繁体   English

如何在React Native中将JSON对象转换为数组

[英]How to convert JSON object into an array in React Native

I am getting a JSON object from Firebase. 我正在从Firebase获取JSON对象。 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. 我可以通过将Firebase中的孩子一个接一个地添加到数组中来解决此问题,但这对我来说不是一个好习惯。

The format of JSON object is as following: JSON对象的格式如下:

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

Now what I want to get from this JSON object is : 现在我想从这个JSON对象得到的是:

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. 这只是普通的javascript,与react native没有关系。 By the way, you can use Object.keys to get an array with all the keys, then map the strings as objects: 顺便说一句,您可以使用Object.keys获取具有所有键的数组,然后将字符串映射为对象:

 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 哪里res.data是我从API得到的响应

Using Object.entries , you can avoid the extra hash lookup on every item. 使用Object.entries ,可以避免对每个项目进行额外的哈希查找。

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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