0

I am trying to create an object using an array that is made using split():

var x = "one two";
var y = x.split(/[^A-Za-z0-9]/)

This gives me an array

[one, two]

Now I want to use that array and create an object using those values, e.g. {one:two}

The following doesn't work:

var z = {};
z.y[0] = y[1];

Can anyone help me out?

1 Answer 1

1

The problem is that your code tries to get the property y on the object z (which doesn't exist), then attempts to use that values as an array and set its first element to y[1]. Obviously, z.y is not an array, it is undefined, so it fails.

You need to use array access notation:

z[y[0]] = y[1];

This will use y[0] as a key instead of interpreting it literally.

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

1 Comment

Thank you, exactly what I wanted!

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.