0

I have an Json array like data {"alphaNumeric":[]}. Here I just want to push the another array [mentioned below] of objects to this Data with out loop concept.

data{"numeric":[{"id":"1","alpha":"a"},{"id":"2","alpha":"b"}]}.

I used the below code : data.alphaNumeric.push(data.numeric);

but the output is :

data{"alphaNumeric":[[{"id":"1","alpha":"a"},{"id":"2","alpha":"b"}]]}.

Expected :

data{"alphaNumeric":[{"id":"1","alpha":"a"},{"id":"2","alpha":"b"}]}.

Help me to resolve.

2
  • that's not an array, that's a javascript object. Can you please show actual code of what you're doing? Reduced to a minimal toy case is fine, but list code that people can run please. Commented Jul 27, 2014 at 9:04
  • .push() and .pop() are for adding and removing single elements in an array. The return value from .concat() is what you're looking for: var newArr = oldArr.concat(extraArr); Commented Jul 27, 2014 at 9:10

3 Answers 3

3

One solution may be using the concat method. Which isn't really good as it creates a whole new array.

b.alphaNumeric = b.alphaNumeric.concat(a.numeric);

But there is a much better solution using push. It accepts more than just one element, but unfortunately not as an array. This can be however achieved using its apply method:

b.alphaNumeric.push.apply(b.alphaNumeric, a.numeric);

Also you can write your own method (I call it add) which will do this action for you:

Array.prototype.add = function (array) {
  this.push.apply(this, array);
  return this;
};

b.alphaNumeric.add(a.numeric);
Sign up to request clarification or add additional context in comments.

Comments

2

Use concat()

data.alphaNumeric.concat(data.numeric);

Comments

0

.push() and .pop() are for adding and removing single elements in an array. The return value from .concat() is what you're looking for:

var newArr = oldArr.concat(extraArr);

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.