以下API返回一些JSON数据:
我正在尝试将Pages对象的属性(也是对象)推送到单个数组中。每个对象应该是数组中自己的元素。
例如,pop
应该被推送到像Scanner input = new Scanner(System.in);
double totalMiles = 0;
double totalGallons = 0;
int tripCounter = 0;
Stack<String> trips = new Stack<>();
while (true){
System.out.print("Enter miles driven: "); //Want to say "Enter miles driven or 'q' to quit: "
String milesInput = input.next();
if(milesInput.equalsIgnoreCase("q") || milesInput.equalsIgnoreCase("quit")){
if(trips.empty()) {
System.out.println("no data entered");
break;
}
String[] previousRecord = trips.pop().split(" ");
System.out.printf("%nYour number of trips is: %s%n", previousRecord[0]);
System.out.printf("Your mileage per gallon of gas consumed is: %s%n%n", previousRecord[1]);
break;
}
double milesDriven = Double.parseDouble(milesInput); // consider adding extra checks before converting
totalMiles = totalMiles + milesDriven;
System.out.print("Enter gallons of gas consumed: "); // Similar to the above.
String gallonsInput = input.next();
if(gallonsInput.equalsIgnoreCase("q") || gallonsInput.equalsIgnoreCase("quit")){
if(trips.empty()) {
System.out.println("no data entered");
break;
}
String[] previousRecord = trips.pop().split(" ");
System.out.printf("%nYour number of trips is: %s%n", previousRecord[0]);
System.out.printf("Your mileage per gallon of gas consumed is: %s%n%n", previousRecord[1]);
break;
}
double gasConsumed = Double.parseDouble(gallonsInput);
totalGallons = totalGallons + gasConsumed;
tripCounter = tripCounter + 1;
double milesPerGallon = totalMiles / totalGallons;
trips.push(tripCounter + " " + milesPerGallon);
System.out.printf("%nYour number of trips is: %s%n", tripCounter);
System.out.printf("Your mileage per gallon of gas consumed is: %s%n%n", milesPerGallon);
}
我这样做是为了让我可以使用ForEach运行数组并使用所需的数据填充DOM。
提前致谢!
答案 0 :(得分:0)
如果您有ES6,似乎只需要它:
var pages = Object.values(response.query.pages);
或者您可以使用此变体使其在旧版浏览器中运行:
var pages = Object.keys(response.query.pages).map(function (key) {
return response.query.pages[key];
});
可以找到更详细的答案here。
答案 1 :(得分:-3)
// result is the json from https://en.wikipedia.org/w/api.php?format=json&action=query&generator=search&gsrnamespace=0&gsrlimit=10&prop=pageimages|extracts&pilimit=max&exintro&explaintext&exsentences=1&exlimit=max&gsrsearch=bananas
const singleArray = Object.keys(result.query.pages).reduce((acc, id) => {
acc.push(result.query.pages[id]);
return acc;
}, []);