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 ?
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 Do you want to concatenate all the appropriate array properties of the objects, or just info? – abesto Commented Feb 2, 2011 at 13:11
3 Answers
Reset to default 5firstObj.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)
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./ahaxu3
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 plexe objects.