开发者

Problem in concatenation of objects in javascript

开发者 https://www.devze.com 2023-02-08 16:26 出处:网络
I have problem in concatenating objects in java script Eg: var firstObj = {}; firstObj.info = [\"sam\",\"kam\"];

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 vir开发者_开发百科tually like concatenating firstObj and secondObj and getting the result in <newObj> or firstObj, How can we achieve this ?


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)


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


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.

0

精彩评论

暂无评论...
验证码 换一张
取 消