2

I have problem in concatenating objects in java script Eg:

var firstObj = {};
firstObj.info = ["sam","kam"];  
var secObj = {};
secObj.info = ["ram","dam"];    

Output that i need :

firstObj.info = ["sam","kam","ram","dam"];

Its virtually like concatenating firstObj and secondObj and getting the result in <newObj> or firstObj, How can we achieve this ?

1
  • 1
    Do you want to concatenate all the appropriate array properties of the objects, or just info? Commented Feb 2, 2011 at 13:11

3 Answers 3

5
firstObj.info = firstObj.info.concat(secObj.info);

The only way to do this is to simply overwrite the info property of object with the conocated array stored at info property of this object and the other obj (or more objects as concat takes multiple number of arguments)

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

Comments

4

Using concat:

var firstObj = {};
firstObj.info = ["sam","kam"];  
var secObj = {};
secObj.info = ["ram","dam"];

var result = firstObj.info;

result = result.concat(secObj.info);

// result = {"sam","kam","ram","dam"}

http://jsbin.com/ahaxu3

Comments

1

If you have two objects of the same structure you should write a concatenation function which concatenates every single variable of that kind of object. You need to take all possible cases in account.

For regular variable types as Strings or simple Arrays this seems easy. You may use the concat function for Arrays and + to concatenate Strings, but it will get difficult if you want to concatenate variables holding complexe objects.

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.