最新消息:Welcome to the puzzle paradise for programmers! Here, a well-designed puzzle awaits you. From code logic puzzles to algorithmic challenges, each level is closely centered on the programmer's expertise and skills. Whether you're a novice programmer or an experienced tech guru, you'll find your own challenges on this site. In the process of solving puzzles, you can not only exercise your thinking skills, but also deepen your understanding and application of programming knowledge. Come to start this puzzle journey full of wisdom and challenges, with many programmers to compete with each other and show your programming wisdom! Translated with DeepL.com (free version)

javascript - foreach loop to fetch JSON - Stack Overflow

matteradmin8PV0评论

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])
}

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])
}

Share Improve this question asked Apr 19, 2018 at 11:29 Juan DavidJuan David 2016 silver badges17 bronze badges 1
  • datesBooking.map(x => x.date) – Satpal Commented Apr 19, 2018 at 11:30
Add a ment  | 

2 Answers 2

Reset to default 4

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)

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.

Post a comment

comment list (0)

  1. No comments so far