user11399165
user11399165

Reputation: 101

How to change object into array

I have an object that I need to change into an array. What is the best approach?

var x = {
    vehicle: {
      manufacturer: "Volkswagen",
      carlineName: "Golf",
    }
}

I want the following result

var x = {
  vehicle: [
    {
      manufacturer: "Volkswagen",
      carlineName: "Golf",
    }
  ]
}

Upvotes: 1

Views: 41

Answers (2)

Jamiec
Jamiec

Reputation: 136104

You just build a new object wrapping your property in [ and ] to make it an array.

var x = {
    vehicle: {
      manufacturer: "Volkswagen",
      carlineName: "Golf",
    }
}

var output = {
  vehicle: [x.vehicle] 
};

console.log(output);

This might be safer than mutating the existing object.

Upvotes: 0

Kobe
Kobe

Reputation: 6446

For this example, you can write:

var x = {
    vehicle: {
      manufacturer: "Volkswagen",
      carlineName: "Golf",
    }
}

x.vehicle = [x.vehicle]

console.log(x)

x.vehicle gets

{
  manufacturer: "Volkswagen",
  carlineName: "Golf",
}

and the square brackets [x.vehicle] place that value into an array:

[{
  manufacturer: "Volkswagen",
  carlineName: "Golf",
}]

We want to reassign x.vehicle with this new value, so we use x.vehicle = [x.vehicle]

Upvotes: 1

Related Questions