0

I have two strings, one a key and one a value, which I would like to turn into an object and concatenate in a loop. For example:

var data = {};
// loop starts here
  var a_key = 'element';
  var a_val = 'value';
  var a_obj = // somehow this equals { "element":"value" }
  data = data.concat(a_obj);
// loop ends here

I'm just not sure how to create an object from those two strings! Any help appreciated

4 Answers 4

1

You should be able to do:

var a_obj = new Object();
a_obj[a_key] = a_val

, no? (I'm not in a position to test this at the moment so take it with a pinch of salt...)

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

Comments

1

Doesn't really make sense to concatenate something to a object without a key. Perhaps data should be an array of objects?

data = [];
a_obj = {};
a_obj[a_key] = a_val;
data += a_obj;

Comments

1
var a_key = 'key';
var a_val = 'value';
var a_obj = {};
a_obj[a_key] = a_val;

Note:

var a_obj = {}

and

var a_obj = new Object();

are the same, but {} feels cleaner and is recommended by Douglas Crockford's JSLint.

For appending objects to other objects, you could do something like... (not tested)

for (var key in a_obj) {
    if (a_obj.hasOwnProperty(key)) { // avoid inherited properties
        data[key] = a_obj[key];
    }
}

Comments

0

var a_key = 'element';

var a_val = 'value';

var a_obj = {a_key:a_val};

1 Comment

This does not do what you expect. You expect a_obj to be {"element":"value"} at the end of this, but it is actually {"a_key":"value"}.

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.