简体   繁体   English

在响应中迭代json数据

[英]iterate json data in react

i am new to react and JSON, i need to process(iterate) some JSON data in react the JSON prototype is given below,"i want console each of the room number which belongings to different category", how can a achieve this using map function 我是新来使用JSON的人,我需要process(iterate)一些JSON数据,以提供JSON原型,如下所示:“我要控制属于不同类别的每个房间号”,如何使用地图来实现功能

please help me out solve the problem. 请帮我解决问题。 "sorry for my bad English, English is not my first language. “对不起,我的英语不好,英语不是我的母语。

let data = {
  "category": {
    "king": [{
        "id": 1,
        "room_no": 101,
        "price": 2000
      },
      {
        "id": 2,
        "room_no": 102,
        "price": 3000
      }
    ],
    "queen": [{
        "id": 1,
        "room_no": 101,
        "price": 2000
      },
      {
        "id": 2,
        "room_no": 102,
        "price": 3000
      }
    ]
  }
} 

It seems you want to iterate over an object like you would do over an array but you don't know how to do it. 似乎您想像遍历数组那样遍历一个对象,但是您不知道该怎么做。

Look into javascript's Object.keys(), Object.values() or Object.entries(). 查看javascript的Object.keys(),Object.values()或Object.entries()。

  • Object.keys(obj) will return an array of keys that can be mapped. Object.keys(obj)将返回可以映射的键数组。

For instance Object.keys({ foo: 1, bar: 2 }) <=> ['foo', 'bar'] 例如Object.keys({ foo: 1, bar: 2 }) <=> ['foo', 'bar']

https://developer.mozilla.org/fr/docs/Web/JavaScript/Reference/Objets_globaux/Object/keys https://developer.mozilla.org/fr/docs/Web/JavaScript/Reference/Objets_globaux/Object/keys

  • Object.values does the opposite: Object.values执行相反的操作:

Object.values({ foo: 1, bar: 2 }) <=> [1, 2] Object.values({ foo: 1, bar: 2 }) <=> [1, 2]

https://developer.mozilla.org/fr/docs/Web/JavaScript/Reference/Objets_globaux/Object/values https://developer.mozilla.org/fr/docs/Web/JavaScript/Reference/Objets_globaux/Object/values

  • And Object.entries() does both. 而Object.entries()两者都可以。

Object.entries({ foo: 1, bar: 2 }) <=> [['foo', 1],['bar', 2]] Object.entries({ foo: 1, bar: 2 }) <=> [['foo', 1],['bar', 2]]

https://developer.mozilla.org/fr/docs/Web/JavaScript/Reference/Objets_globaux/Object/entries https://developer.mozilla.org/fr/docs/Web/JavaScript/Reference/Objets_globaux/Object/entries

So for you a way to map your object is to do: 因此,对您来说,映射对象的方法是:

Object.keys(data.category).map(function(categoryName) {
    var category = data.category[categoryName];
    category.map(function(bed) {
        console.log(
            'Category: , ', categoryName,
            ' / Bed: ', bed.id,
            ' / Room number: ', bed.room_no
        );
    });
});

Working fiddle here (remember to open the console to see the result) 在这里工作(请打开控制台以查看结果)

You cannot actually do this using map alone. 实际上,您不能仅使用地图来完成此操作。 Or at least, it would be counter to how map is usually used. 至少,这与通常使用map方式背道而驰。

You can use multiple map steps to convert the object to a nested list —in this case a list of list of lists of objects—; 您可以使用多个map步骤将对象转换为嵌套列表(在这种情况下为对象列表列表)。 but you will also need to flatten the result of the map to a list of numbers. 但您还需要将map的结果展平为数字列表。 See here: 看这里:

 let data = { "category": { "king": [{ "id": 1, "room_no": 101, "price": 2000 }, { "id": 2, "room_no": 102, "price": 3000 } ], "queen": [{ "id": 1, "room_no": 101, "price": 2000 }, { "id": 2, "room_no": 102, "price": 3000 } ] } }; const room_nos = Object.values(data) .map(entry => Object.values(entry) .map(category => category.map(room => room.room_no))) .reduce((result, array) => result.concat(array), []) .reduce((result, array) => result.concat(array), []); console.log(room_nos); 

First, there's three nested map steps. 首先,有三个嵌套的map步骤。 The first two use Object.values to convert the objects to lists of their values (one for data and one for category ). 前两个使用Object.values将对象转换为其值的列表(一个用于data ,另一个用于category )。 This gives you a list of list of lists of room descriptors (ie objects with id , room_no and price properties). 这为您提供了房间描述符列表的列表(即,具有idroom_noprice属性的对象)。 In the third map step the room descriptors are projected on the room_no properties to obtain a list of list of lists of numbers. 在第三个map步骤中,将房间描述符投影到room_no属性上,以获取数字列表的列表。

Secondly, we flatten the list of list of lists of numbers to a list of numbers using two reduce steps. 其次,我们使用两个reduce步骤将数字列表的列表扁平化为数字列表。

OUTPUT: OUTPUT:

[
  101,
  102,
  101,
  102
]

UPDATE: you can convert the inner list to a list of elements with type { [category: string]: number } as follows: 更新:您可以将内部列表转换为类型{ [category: string]: number }的元素列表,如下所示:

  let data = { "category": { "king": [{ "id": 1, "room_no": 101, "price": 2000 }, { "id": 2, "room_no": 102, "price": 3000 } ], "queen": [{ "id": 1, "room_no": 101, "price": 2000 }, { "id": 2, "room_no": 102, "price": 3000 } ] } }; const room_nos = Object.values(data) .map(entry => Object.entries(entry) .map(([category, rooms]) => rooms.map(room => ({ [category]: room.room_no })))) .reduce((result, array) => result.concat(array), []) .reduce((result, array) => result.concat(array), []); console.log(room_nos); 

OUTPUT: OUTPUT:

[
  {
    "king": 101
  },
  {
    "king": 102
  },
  {
    "queen": 101
  },
  {
    "queen": 102
  }
]

For consoling room_no : 对于安慰room_no

[].concat.apply([], Object.values(data["category"])).map(i => console.log(i.room_no))

Output: 输出:

101
102
101
102

Object.values(data["category"]) gives the values of king and queen categories in a nested array format and [].concat.apply([], [nested_array]) flattens it to a single level array in which Array.prototype.map() is applied Object.values(data["category"])以嵌套数组格式给出国王和王后类别的值,然后[].concat.apply([], [nested_array])将其展平为其中Array.prototype.map()的单级数组Array.prototype.map()被应用

For formatting the result like category : room_no : 用于格式化结果,例如category:room_no

for(key in data["category"]){
  data["category"][key].map(i => console.log(`${key} : ${i.room_no}`))
}

Output: 输出:

king : 101
king : 102
queen : 101
queen : 102

Here looped over data["category"] and applied Array.prototype.map() . 这里遍历data["category"]并应用Array.prototype.map()

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

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