如何从对象返回值?
Posted
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了如何从对象返回值?相关的知识,希望对你有一定的参考价值。
有一个带有数组参数的函数。对我来说,有必要推导出通过符号“ - ”的行中对象的值。例如:[“BMW-55 000-Germany-Hight”,“Mitsubishi-93 000-Bar John-3-Japan”,“Mercedes-benz-63 000-Germany-Hight”]。哪里出错了?
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 joinArr(car){
return Object.values(car).forEach(function(){
return car.join("-")
});
}
答案
你可以使用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 joinArr(car) {
return car.map(o => Object.values(o).join("-"));
}
var result = joinArr(car);
console.log(result);
另一答案
car
不是一个对象,而是一个对象数组。您可能想要映射(并将car
重命名为cars
以避免混淆):
function joinCars(cars) {
return cars.map(function(car) {
return Object.values(car).join("-");
});
}
另一答案
forEach
不返回任何东西 - 只需使用join
:
function joinArr(car){
return Object.values(car).join("-");
}
要对完整数组执行此操作并获取字符串数组,请使用map
。还可以考虑重命名参数:
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"
}
];
const joinArr = cars => cars.map(car => Object.values(car).join("-"));
console.log(joinArr(cars));
以上是关于如何从对象返回值?的主要内容,如果未能解决你的问题,请参考以下文章