0

im trying to build a cart functionality where the user would add a single product to an array of products or objects.

  var product = {
                    "Name": "Bike",
                    "Price": "900",
                    "idproduct": "1"
                };

now i would like to store this product in plain json text.Stringify function does just that.

var JsonString = JSON.stringify(product); 

Now i would like to take that JsonString and convert it back to an object or object array like so.

var JsonObjectArray  = JSON.parse(JsonString);

Now im going to create a new exactly the same json object type but with diff values.

var product2 = {
                    "Name": "Car",
                    "Price": "12000",
                    "idproduct": "2"
                };

It seems that JsonObjectArray doesnt have the push method because it got deserialized into a single object namely product1, what should i do so i can add product2 to JsonObjectArray as another member of the aray like so and repeat the process multiple times.

JsonObjectArray.push(product2);
1
  • 2
    Isn't push for arrays? You've got objects here right? Commented Jun 25, 2014 at 23:01

1 Answer 1

3

Starting with product as you have defined it, you will want to do one of the following:

  • Use JSON.stringify([product]) so that JsonString will be an JSON array:

    var JsonString = JSON.stringify([product]);
    var JsonObjectArray = JSON.parse(JsonString);
    
  • Leave JsonString as a single object, but create a one element array from the result of JSON.parse:

    var JsonString = JSON.stringify(product);
    var JsonObjectArray = [JSON.parse(JsonString)];
    
Sign up to request clarification or add additional context in comments.

2 Comments

I would define a products variable for clarity, and so you have access to the array without having to stringify and parse 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.