0

I am trying to set a url with an object I have created (in angular). It is an object array I would let to set on the url string to do a kind of "save state".

I have my object like -

  [{"key1" : true}, {"key2" :  false}];

And I basically want to set that as a url object so I can get a custom url string for my state - which would then be interpreted on landing to change a state (so users can send custom urls).

So before when it was just one object, I could pass the object and do something like

$scope.myObject = true;
$location.search($scope.myObject);

But I am trying to combine a few of the objects into one big object so I can keep track of a few different states in one place (in a factory). The problem I am having is I cannot seem to get it to work if the the location.search parameter is an array of objects. I'm getting an "undefined is not a function" and it's pointing inside angular.

Are there any tricks to this? Could use some help, this is my first time trying this. Also, I'm trying to change the url without refreshing. Thanks!

1
  • 2
    Your object is an array of objects thus not an object but an array. An object starts { and ends }. An object can contain array(s). Commented Mar 3, 2015 at 16:55

1 Answer 1

1

Instead of:

[{"key1" : true}, {"key2" :  false}];

Try:

{"key1" : true, "key2" :  false};

That is the correct JSON syntax for "one big object".

To go from an array of objects to one big object, you must iterate through the array and build a new object with the properties uncovered from the array:

var newObj = {};
var oldArray = [{"key1" : true}, {"key2" :  false}];
for (var i = 0; i < oldArray.length; i++) {
    var obj = oldArray[i];
    for (param in obj) {
        newObj[param] = obj[param];
    }
}
// newObj is now one big object.
Sign up to request clarification or add additional context in comments.

4 Comments

Ah, is there a way to turn an array of objects into 1 object?
@ajmajmajma how about var obj= {"array1":[{"key1" : true},{"key2" : false} ]}
@ajmajmajma, if this syntax does not come naturally, I highly recommend brushing up on your JSON syntax. It's quite simple and it will prove to be very helpful when writing object oriented javascript.
For some reason I was thinking it could take an array of objects (I don't know why), thank you for your help - this helped me solve it.

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.