我和Promise都返回了一个对象,我想循环遍历该对象以按价格排序,但是我无法操纵返回的对象,而且我也不知道为什么。
如果我只是console.log
的结果(就像我在第二个console.log上所做的那样),它将显示值,但是如果我做任何我在网络上建立的操作,它们将返回空数组。
这是我的代码:
getPrices().then(res => {
console.log(typeof res);
// console -> object
console.log('result', res);
// console -> [] {0: {price: "12.80", competitor: "competitor 1")...} length: 7 __proto__: Array(0)
console.log('stringfy', JSON.stringify(res));
// console -> stringfy []
console.log('array from', Array.from(res));
// console -> [] length: 0 __proto__: Array(0)
console.log('object keys', Object.keys(res));
// console -> [] length: 0 __proto__: Array(0)
});
我还尝试过在Object.entries
上直接使用map
和res
如何正确地将此对象转换为数组并使用.sort或.map?
这是我的gitPrice函数:
export const getPrices = async () => {
const prices = [];
data.map(index => {
request(index.link, (error, response, html) => {
if (!error && response.statusCode == 200) {
let che, price, newItem;
che = cheerio.load(html);
price = (index.selector.includes("itemprop")) ? che(index.selector).attr('content') : che(index.selector).text();
newItem = {
"price": price,
"competitor": index.competitor
};
prices.push(newItem);
} else {
console.error(`ERROR ${response.statusCode}: Was not possible to scrap the ${index.competitor}: `)
}
});
});
return prices;
}
答案 0 :(得分:1)
这是一个常见的初学者问题,您尝试获取结果数组,但应获取承诺数组,然后全部解决
import {Component} from '@angular/core';
import {FormControl} from '@angular/forms';
@Component({
selector: 'select-multiple-example',
templateUrl: 'select-multiple-example.html',
styleUrls: ['select-multiple-example.css'],
})
export class SelectMultipleExample implements OnInit {
toppings = new FormControl(['Extra cheese']);
toppingList: string[] = ['Extra cheese', 'Mushroom', 'Onion', 'Pepperoni','Sausage', 'Tomato'];
}