0

I want to construct an object, where one of the property is going to be an array:

var a = 1;
var b = ["a","b"]
var b1 = ["c","d"]
var c = {}

I want the object c to be like this:

{"prop":1, prop1: ["ac","bd"]}

I tried doing it like this:

c.prop = a;
for (var index = 0 ; index < b.length; index++){
    c.prop1[index] = b[index] + b1[index];
}
4
  • do you mean just c.prop = a; c.prop1 = b? Commented Jan 19, 2015 at 5:24
  • I just edited the question. I want to do processing. So I want to add element one by one. Not directly like c.prop1 = b Commented Jan 19, 2015 at 5:25
  • 1
    What's the value of c.prop1 before your for loop? If c.prop1 isn't defined yet, you can't set properties on it with c.prop1[index] = ..., and you'll see errors in your JavaScript console to that effect. Commented Jan 19, 2015 at 5:27
  • Thanks Jordan. I got the answer from your comment. Commented Jan 19, 2015 at 5:29

3 Answers 3

2

You can initialize the property prop1 in your object as an empty array [] and then add the proper objects to it using push method. The code:

var a = 1;
var b = ["a","b"]
var b1 = ["c","d"]
var c = {}
c.prop = a;
c.prop1 = []; // initialization
for (var index = 0 ; index < b.length; index++){
    c.prop1.push(b[index] + b1[index]); // pushing computed values
}
Sign up to request clarification or add additional context in comments.

1 Comment

Answers with an explanation (more than just code) that explain why or what was changed are generally better than answers that are just code. You could improve this answer by explaining.
1

I think you need to define your array prop1 first, before you can start adding values to it;

c.prop = a;
c.prop1 = [];       // declare prop1 to be an empty array
for (var index = 0 ; index < b.length; index++){
    c.prop1[index] = b[index] + b1[index];
}

Comments

1
var associativeArray = {};
associativeArray["one"] = [];
associativeArray["two"] = [];
associativeArray["three"] = [];

If you are coming from OO Language then you should have a look at this

1 Comment

Thanks for that link Ancient.

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.