简体   繁体   English

如何在反应原生中将数据作为JSON树推送到数组中?

[英]How to push data into array as a JSON tree in react native?

I'm developing a mobile app using React Native. 我正在使用React Native开发移动应用程序。 I need to put some data into an array with categories (SubKeys / Children). 我需要将一些数据放入带有类别(SubKeys / Children)的数组中。 I have data stored in Firebase Real-time Database. 我有数据存储在Firebase实时数据库中。 So, I want to push those data into an array as that JSON tree exists. 因此,我希望将这些数据推送到数组中,因为存在JSON树。 For example, I want to build an array like following. 例如,我想构建一个如下的数组。 There is a category named 'Fruits'. 有一个名为'Fruits'的类别。 Under that, it has 'Apple', 'Strawberry', etc. Like this, for other categories as well. 在此之下,它有'Apple','Strawberry'等。像这样,对于其他类别。

const items = [
    {
      name: 'Fruits',
      id: 0,
      children: [
        {
          name: 'Apple',
          id: 10,
        },
        {
          name: 'Strawberry',
          id: 17,
        },
        {
          name: 'Pineapple',
          id: 13,
        },
        {
          name: 'Banana',
          id: 14,
        },
        {
          name: 'Watermelon',
          id: 15,
        },
        {
          name: 'Kiwi fruit',
          id: 16,
        },
      ],
    },
    {
      name: 'Gems',
      id: 1,
      children: [
        {
          name: 'Quartz',
          id: 20,
        },
        {
          name: 'Zircon',
          id: 21,
        },
        {
          name: 'Sapphire',
          id: 22,
        },
        {
          name: 'Topaz',
          id: 23,
        },
      ],
    },
    {
      name: 'Plants',
      id: 2,
      children: [
        {
          name: "Mother In Law's Tongue",
          id: 30,
        },
        {
          name: 'Yucca',
          id: 31,
        },
        {
          name: 'Monsteria',
          id: 32,
        },
        {
          name: 'Palm',
          id: 33,
        },
      ],
    },
  ];

let's consider input having value as we expect: 让我们考虑输入具有我们期望的价值:

let output=[]
for(let i=0;i<input.length;i++){
  let obj={};
  obj.name = input[i].name
  obj.id = input[i].id
  obj.children = [ ...input.children]
  output.push(obj);
}

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

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