0

I have an array object now. The function should return an array of arrays of all object values. Where is the mistake?

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));
Fullstack Guy
  • 16,368
  • 3
  • 29
  • 44
Gregori Roberts
  • 309
  • 3
  • 10
  • `key` references each object in your array, so you go from this: `[{}, {}, ...]` to this `[[[{}]], [[{}]], ...]`. Show the structure you want. – Adrian Lynch Apr 21 '19 at 11:31
  • Possible duplicate of [How to convert an Object {} to an Array \[\] of key-value pairs in JavaScript](https://stackoverflow.com/questions/38824349/how-to-convert-an-object-to-an-array-of-key-value-pairs-in-javascript) – 1565986223 Apr 21 '19 at 11:31
  • 1
    please add the wanted result. – Nina Scholz Apr 21 '19 at 11:32

3 Answers3

3

You could return the values of the object.

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; }
Nina Scholz
  • 376,160
  • 25
  • 347
  • 392
0

You are wrapping the individual array object in another array so it becomes [[{object}]], simply map to a new array of Object.values of the inner objects.

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));
Fullstack Guy
  • 16,368
  • 3
  • 29
  • 44
0

Change [[key]] to [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));
Junius L
  • 15,881
  • 6
  • 52
  • 96