Home > Net >  JavaScript - How can I reference an item in JSON like variable?
JavaScript - How can I reference an item in JSON like variable?

Time:12-10

Consider I have the following variable:

var result = {
    "Items": [
      {
        "location": "New York",
        "visible": false,
        "destinations": [
          4,
          3,
          5
        ],
        "id": 3,
        "coordinates": {
          "lng": -74.17,
          "lat": 40.68
        }
      },{
        "location": "Madrid",
        "visible": false,
        "destinations": [
          0,
          4
        ],
        "id": 0,
        "coordinates": {
          "lng": -3.56,
          "lat": 40.49
        }
      },
      {
        "location": "Los Angeles",
        "visible": false,
        "destinations": [
          4,
          3,
          5
        ],
        "id": 5,
        "coordinates": {
          "lng": -118.4,
          "lat": 33.94
        }
      }
    ]
  };

If I want to reference to Los Angeles, I would do as below and it works great:

  console.log(result.Items[2]);

What if I don't know the order but I know its id (5). How can I reference it by its ID?

CodePudding user response:

You can't reference it directly, but you can use some Javascript function on the array to find it, such as:

result.Items.find(x => x.id == 5);

Reference: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/find

CodePudding user response:

Filter your input like that

let newFilteredArray = result.filter(item => {
    return item.id === 5;
};
console.log(newFilteredArray[0];

CodePudding user response:

var id = 2

You can set id same as index and console.log(result.Items[id]) example:

var result = {
    "Items": [
      {
        "location": "New York",
        "visible": false,
        "destinations": [
          4,
          3,
          5
        ],
        "id": 0,
        "coordinates": {
          "lng": -74.17,
          "lat": 40.68
        }
      },{
        "location": "Madrid",
        "visible": false,
        "destinations": [
          0,
          4
        ],
        "id": 1,
        "coordinates": {
          "lng": -3.56,
          "lat": 40.49
        }
      },
      {
        "location": "Los Angeles",
        "visible": false,
        "destinations": [
          4,
          3,
          5
        ],
        "id": 2,
        "coordinates": {
          "lng": -118.4,
          "lat": 33.94
        }
      }
    ]
  };
  • Related