0

I'm trying to parse an incoming json string and push a new object to that.

I've tried it like this:

addSetting(category) {
    console.log(category.value); //Console.log = [{"meta":"","value":""}]
    category.value = JSON.parse(category.value).push({meta: "", value: ""});
    console.log(category.value); //Console.log = 2
},

Problem is that category.value is 2? I would expect 2 json objects? What am I doing wrong here?

1
  • 1
    What you're doing by this category.value = JSON.parse(category.value).push({meta: "", value: ""}); is simply assigning the return value of the push operation to category.value which before now doesn't exist. Commented Oct 29, 2017 at 11:37

1 Answer 1

1

Try:

addSetting(category) {
 category.value = JSON.parse(category.value);
 category.value.push({meta: "", value: ""});
 console.log(category.value);
}

You are using push() incorrectly. The array function push() returns the size of the new array.

Return value

The new length property of the object upon which the method was called.

ref:Array.prototype.push() MDN

As the new size of your array will be 2 (after pushing the new element) the following line was incorrect:

category.value = JSON.parse(category.value).push({meta: "", value: ""});

As after JSON was parsed, the variable category.value was assigned the return value of push.

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.