我现在有一个数组对象。该函数应返回一个包含所有对象值的数组的数组。错误在哪里?
const car = [
{
"name":"BMW",
"price":"55 000",
"country":"Germany",
"security":"Hight"
},
{
"name":"Mitsubishi",
"price":"93 000",
"constructor":"Bar John",
"door":"3",
"country":"Japan",
},
{
"name":"Mercedes-benz",
"price":"63 000",
"country":"Germany",
"security":"Hight"
}
];
function cars(car){
return car.map(function(key) {
return [[key]];
});
}
console.log(cars(car));
答案 0 :(得分:5)
您可以返回对象的值。
function cars(car){
return car.map(Object.values);
}
const car = [{ name: "BMW", price: "55 000", country: "Germany", security: "Hight" }, { name: "Mitsubishi", price: "93 000", constructor: "Bar John", door: "3", country: "Japan" }, { name: "Mercedes-benz", price: "63 000", country: "Germany", security: "Hight" }];
console.log(cars(car));
.as-console-wrapper { max-height: 100% !important; top: 0; }
答案 1 :(得分:0)
您将单个数组对象包装在另一个数组中,这样它就变成[[{object}]]
,简单地map
到内部对象Object.values
的新数组中。
const car = [
{
"name":"BMW",
"price":"55 000",
"country":"Germany",
"security":"Hight"
},
{
"name":"Mitsubishi",
"price":"93 000",
"constructor":"Bar John",
"door":"3",
"country":"Japan",
},
{
"name":"Mercedes-benz",
"price":"63 000",
"country":"Germany",
"security":"Hight"
}
];
function cars(car){
return Array.from(car, Object.values)
}
console.log(cars(car));
答案 2 :(得分:0)
将[[key]]
更改为[key]
const car = [
{
"name":"BMW",
"price":"55 000",
"country":"Germany",
"security":"Hight"
},
{
"name":"Mitsubishi",
"price":"93 000",
"constructor":"Bar John",
"door":"3",
"country":"Japan",
},
{
"name":"Mercedes-benz",
"price":"63 000",
"country":"Germany",
"security":"Hight"
}
];
function cars(car){
return car.map(function(key) {
return [key];
});
}
console.log(cars(car));