JSON对象 - 在React Native中访问值 [英] JSON object - Accessing Values in React Native

查看:90
本文介绍了JSON对象 - 在React Native中访问值的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在我的React Native应用程序中,我使用的是RNDBModels包,它是AsyncStorage的包装器。目前我正在通过RNDBModel保存一个JSON对象并且工作正常,但访问数据证明具有挑战性。

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.

当代码从返回时得到方法,它返回一个JSON对象,我基本上喜欢结果中的值,这样我就可以遍历它以获得一个列表。

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.

返回的结果:

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

以及所需的结果,以便我可以轻松地迭代数组中的对象,然后在React Native中呈现一个列表。

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 
  }
 ]

访问价值的任何建议?我已经尝试使用 Object.keys ,然后随后 Object.values 无可救药。

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

推荐答案

你可以用 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

这篇关于JSON对象 - 在React Native中访问值的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆