1

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",
    }
  ]
}
1
  • 1
    x.vehicle = [x.vehicle] Commented Jun 17, 2019 at 15:17

2 Answers 2

1

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]

Sign up to request clarification or add additional context in comments.

Comments

0

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.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.