0

I'm having a stupid issue, probably due to my syntax. How can I dynamically push all keys from object arr[j] into object arr[i]?

var arr = [{key:["data1","data2"]},{key:"data"}];
var i = 0;
var j = 1;
for(var key in arr[i]){
     arr[i][key].push(arr[j][key]);
     // arr[i][key] is an array, arr[j[key;] is a string
}

Rather than brutally typing everything out (which works for me):

arr[i][key1].push(arr[j].key1);
arr[i][key2].push(arr[j].key2);

Arr[i] will then contain its previous information and object 2 information in the form of an array. Basically, I'm concatenating JavaScript objects. In the end, arr[i] should look like:

key1:[arr[i].key1Value,arr[j].key1Value]
key2:[arr[i].key2Value,arr[j].key2Value]

Thanks in advance!!

2
  • Can you add the expected output to your question as it's not clear to me what you want to do. Commented Nov 18, 2015 at 11:59
  • @Andy put it in there. Basically I'm just concatenating JavaScript objects into an array. Commented Nov 18, 2015 at 12:02

2 Answers 2

1

Relatively simple:

var arr = [{key:["data1","data2"]},{key:"data"}],
    i = 0,
    j = 1,
    target = arr[i],
    source = arr[j];

target.key.push(source.key);

If the source has multiple keys, try this instead:

var arr = [{key:["data1","data2"]},{key:"data", key1: "data1", key2: "data2"}],
    i = 0,
    j = 1,
    target = arr[i],
    source = arr[j];

for(var key in source){           // Loop over the keys in the source
    target.key.push(source[key]); // And add them to the target's `key` array.
}

Result:

[
    { key: ["data1", "data2", "data", "data1", "data2"]},
    { key: "data", key1: "data1", key2: "data2"}
]
Sign up to request clarification or add additional context in comments.

2 Comments

Nice solution, this does it!
So, this is the output you were looking for? I'm happy to be of help! Thanks for accepting the answer :-)
0

I am not 100% sure if I understand what you try to achieve but maybe this helps:

var arr = [{key:["data1","data2"]},{key:"data"}];
var target = [];

arr.forEach( function(value,index){
   target['key' + index] = value;

});

Output:

target.key0 : { key: [ 'data1' 'data2' ]}
target.key1 : { key: [ 'data' ]}

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.