-3

I have several objects like this and wonder how I can search between these, say that we got the number 1 and want to figure out what the name is. Should I loop it or what do you guys suggest?

To make things clear, I do want to get the other objects by using the number. Is it possible?

    {
      "room": [
          {
              "number": "1",
              "name": "room1"
          },
          {
              "number": "2",
              "name": "room2"
          }
      ]
   }
J. Jesper
  • 117
  • 2
  • 11
  • Possible duplicate of [Find a value in an array of objects in Javascript](https://stackoverflow.com/questions/12462318/find-a-value-in-an-array-of-objects-in-javascript) – JJJ Mar 11 '18 at 15:08

3 Answers3

1

Firstly, bring in the file. Make sure to include the './' before the file name to show that it's from the current directory.

const data = require('./data.json');

Now the JSON data is stored inside the variable data. To access the members, use the dot operator. data.room will return the array of rooms.

To access the individual room, use data.room[i] where i is the numbered element in the array (starting from 0). For example, to access the first room:

const first_room = data.room[0];

This first_room variable can now be used to access the name.

console.log(first_room.name);

This will log "room1" to the console.

Jake
  • 75
  • 6
1

You could use a map and use the room number as identifier. This way you can access the room data via the room number like that:

var data = {
    "room": [
        {
            "number": "1",
            "name": "room1"
        },
        {
            "number": "2",
            "name": "room2"
        }
    ]
};
// or load it from a file:
// var data = require('./data.json');
   
var rooms = new Map();
for(room of data.room) {
    rooms.set(Number(room.number), room);
}
// access data for room with number 1
alert(rooms.get(1).name);
saitho
  • 899
  • 9
  • 17
0

You can try this. This will help you.

var roomData =  {
      "room": [
          {
              "number": "1",
              "name": "room1"
          },
          {
              "number": "2",
              "name": "room2"
          }
      ]
   }
   
for(key in roomData.room){
  console.log("Room Number - " + roomData.room[key].number);
  console.log("Room Name - " + roomData.room[key].name);
}
A.K.
  • 2,284
  • 3
  • 26
  • 35