最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

Problem in concatenation of objects in javascript - Stack Overflow

programmeradmin1浏览0评论

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 ?

Share Improve this question edited Feb 2, 2011 at 13:09 Thariama 50.8k13 gold badges145 silver badges175 bronze badges asked Feb 2, 2011 at 13:08 manohar_tnmanohar_tn 1011 silver badge10 bronze badges 1
  • 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
Add a ment  | 

3 Answers 3

Reset to default 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)

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.

发布评论

评论列表(0)

  1. 暂无评论