1

Just a question about JS object structuring. I have an object called mainObject I want to push values in so they appear in a format like the second section of code. The values will be added in a loop. I want to be able to do something along the lines of:-

mainObject.data.push({lat : val['lat'], lng: val['lng'], count: 40});} 

Could someone tell me how I can go about doing this? Trying to get my head around JS objects.

var mainObject = {
    max: 46};

var mainObject = {
            max: 46,
            data: [{lat: 33.5363, lng:-117.044, count: 1},{lat: 33.5608, lng:-117.24, count: 1},{lat: 38, lng:-97, count: 1},{lat: 38.9358, lng:-77.1621, count: 1}]
    };

Thanks :)

2
  • It depends. Where are the values coming from? Array? Object? Commented Mar 12, 2013 at 15:57
  • Why do you have var mainObject twice? With the second one, your push code should work well Commented Mar 12, 2013 at 16:05

1 Answer 1

2

In javascript .push is reserved for arrays. To add to an object that already has a property you can simply do this.

var mainObject = {
    max: 46
};

mainObject.data = [{lat : val['lat'], lng: val['lng'], count: 40}];

You would then end up with an object that looked like this:

mainObject{
    max : 46,
    data : [{lat : val['lat'], lng: val['lng'], count: 40}]
}

Which is what you wanted.

EDIT:

@cristoph pointed out that if you change the instansiation of your initial mainObject then you could do this:

 var mainObject = {
     max : 46,
     data : [] 
 }

 mainObject.data.push({lat : val['lat'], lng: val['lng'], count: 40});

Which would give you the same result.

Either way you choose to do it, once data is a property of mainObject and is an array, you can then continue to use .push to insert more elements into it.

So doing this to the above:

 mainObject.data.push({foo : bar});

Would yield:

 mainObject{
     max : 46,
     data : [{lat : val['lat'], lng: val['lng'], count: 40}, {foo : bar}]
 }
Sign up to request clarification or add additional context in comments.

4 Comments

push is perfectly fine if he has mainObject{max:46,data:[]}. So probably the only thing OP needs to change is the initialisation of the mainObject.
@Christoph yes if he already has the data property and it's value is an array. I believe that he wanted to add a new property, which you would do with the code that I presented
But what if I'm pushing multiple items?
@user1840255 see my newest update, that should answer all your questions.

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.