0
let new_json = {
  sessions: []
};

new_json.sessions[0]["timing"] = []

Error:

VM73:1 Uncaught TypeError: Cannot set property 'timing' of undefined
    at <anonymous>:1:32
(anonymous) @ VM73:1

Here I am trying to add data to one index of the array

But, getting above error while doing this.

Is there any way to do this?

Please have a look

1
  • 1
    Your sessions arrays has no value at index 0. So new_json.sessions[0] will give undefined. This results in an error when you try and set a property of "timing" on undefined. Instead, you can set the value of index 0 to be an object literal, with the property of timing and an array value. Or, initialize your sessions array with an empty object [{}] Commented Feb 29, 2020 at 4:42

3 Answers 3

3

First initialize the object at 0th position and the add the value like this

new_json.sessions[0] = {};
new_json.sessions[0]["timing"] = []
Sign up to request clarification or add additional context in comments.

Comments

1

You can do this by pushing the new object with timing property into the sessions array,

let new_json = { sessions: [] };

new_json.sessions.push({ timing: [] })
console.log(new_json.sessions)

Comments

1

This would work:

new_json.sessions[0] = { timing: []}

In JavaScript you can, if you want, set the value of an arbitrary index in an array. But you cannot assign the property of an unassigned value at an arbitrary index, as your code attempts to do. That is accessing the value at the index, not setting the value.

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.