Juan David
Juan David

Reputation: 201

foreach loop to fetch JSON

I'm trying to make this json

{"date":"04\/24\/2018"},
{"date":"04\/25\/2018"}

print the values as follows

['04/24/2018', '04/25/2018']

But I could not do it, any suggestions?

var datesBooking = [
{"date":"04\/24\/2018"},
{"date":"04\/25\/2018"}
];

for(var key in datesBooking){
  console.log(datesBooking[key])
}

Upvotes: 1

Views: 3692

Answers (2)

user4447799
user4447799

Reputation:

If you are explicitly looking for the foreach method:

var datesBooking = [
  {"date": "04\/24\/2018"},
  {"date": "04\/25\/2018"}
];

datesBooking.forEach(function(data, index) {
  datesBooking[index] = data.date;
});

console.log(datesBooking);

The above code will rewrite over the existing array.

The same can be achieved using map

var datesBooking = [
  {"date": "04\/24\/2018"},
  {"date": "04\/25\/2018"}
];

datesBooking = datesBooking.map(x => x.date);

console.log(datesBooking);

As you can see, the map was introduced to simplify such a use of foreach.

The map() method creates a new array with the results of calling a provided function on every element in the calling array.

Upvotes: 2

Mihai Alexandru-Ionut
Mihai Alexandru-Ionut

Reputation: 48407

You could use map method by passing a provided callback function.

var datesBooking = [
{"date":"04\/24\/2018"},
{"date":"04\/25\/2018"}
];
console.log(datesBooking.map(function(item){
  return item.date;
}));

Another approach is simply using arrow functions.

datesBooking.map(a => a.date)

Upvotes: 4

Related Questions