简体   繁体   中英

How can I iterate an array of arrays and keep only values from a single index in javascript? [duplicate]

I am building a booking calendar using easepicker and importing data using a third-party API in a mySQL db. I got the data in the database and I can access it in Javascript (to which I'm new). I'm trying to remove all indexes but one from an array of arrays, but no matter how I try to do the loop I get a .pop() undefined, although I made sure the object is an array of arrays.

$.ajax({
  url     : 'get_data.php', // this fetches the booking info from 3rd party => DB
  type    : 'GET',          // type of the HTTP request
  success : checkAvail,
});


function checkAvail(response) {
  results     = response;
  var results = jQuery.parseJSON(response);
  availables  = results.filter(a => a.isAvailable === '1');

  console.log(availables); // displays the array of arrays for avail dates


  availables.forEach((available) => {
    available.pop(2); // **Uncaught TypeError: available.pop is not a function
  });

  console.table(availables);
}

console.log(availables) output

[
    {
        "id": "79653836",
        "date": "2022-07-09",
        "isAvailable": "1",
        "price": "2188"
    },
    {
        "id": "79653838",
        "date": "2022-07-10",
        "isAvailable": "1",
        "price": "1750"
    },
    {
        "id": "79653840",
        "date": "2022-07-11",
        "isAvailable": "1",
        "price": "1750"
    },
    {
        "id": "79653842",
        "date": "2022-07-12",
        "isAvailable": "1",
        "price": "1750"
    }
]

availables is an array of objects, not an array of arrays.

To get a particular property from an object, use .propname , so use available.date to get the date.

You can use map() to return a new array that uses this to get the properties.

 const availables = [ { "id": "79653836", "date": "2022-07-09", "isAvailable": "1", "price": "2188" }, { "id": "79653838", "date": "2022-07-10", "isAvailable": "1", "price": "1750" }, { "id": "79653840", "date": "2022-07-11", "isAvailable": "1", "price": "1750" }, { "id": "79653842", "date": "2022-07-12", "isAvailable": "1", "price": "1750" } ]; const dates = availables.map(a => a.date); console.log(dates);

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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