0

This is a basic question but I'm just curious about an elegant way to do something (I already have solution for dirty way). I have the code below to start with empty var a as JSON array. Then I want to concat more JSON objects array into it later on:

var a = [{}];
a = a.concat([{"a":"b1"},{"a":"b2"}]);
a.splice(0,1); // This does not work to remove index 0 of undefined
console.log(a[0].a + " " + a[1].a + " " + a[2].a);

The problem is when a declared, it already came with undefined in index 0. I could re-generate the whole array to remove all undefined using push.apply() but that seems unnecessary overhead. See:

Javascript: How to remove an array item(JSON object) based on the item property value?

Two questions:

  1. Is there a way to concat arrays but override the index 0 on initial concat?
  2. OR is there a way to use concat without declaring it a = [{}]?
5
  • 2
    Why don't you use a = []? Commented May 21, 2013 at 20:25
  • 1
    There's really no such thing as a "JSON array" in JavaScript. It's just an array. Commented May 21, 2013 at 20:26
  • Also your array "a" does not have undefined in index 0; it has an empty object. If you declare the array with just [], then it will have a length of 0. Commented May 21, 2013 at 20:27
  • Are you aware your error comes from a[2].a at the console.log line? At that point, there's not a[2]. Before the console.log call, there's no error. Commented May 21, 2013 at 20:28
  • Ops! Dumb mistake on my end. Thanks guy. Commented May 21, 2013 at 22:59

1 Answer 1

5

You should just be declaring it as an empty array, there is no need for the empty object inside.

var a = [];

Output in a console

> var a = [];
  undefined
> a = a.concat([{"a":"b1"},{"a":"b2"}]);
  [Object, Object]
Sign up to request clarification or add additional context in comments.

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.