3

everyone!

I have an array containing some strings:

strs = ['a1','a2','a3']

and an object is defined:

o={}

I wanna add properties to o while the property name is the string in array strs Any suggestion is appreciated

2 Answers 2

4

Try the following

for (var i = 0; i < strs.length; i++) {
  var name = strs[i];
  o[name] = i;
}

This code will create the properties with the given name on the object o. After the loop runs you will be able to access them like so

var sum = o.a1 + o.a2 + o.a3;  // sum = 3

Here's a fiddle which has some sample code

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

Comments

1

This can be done using Square Bracket Notation.

var strs = ['a1','a2','a3'];
var o = {};

for(i = 0; i<strs.length; i++)
{
    o[strs[i]] = "value";
}

document.write(o.a1);

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.