0

I have read SO and others but more complex For referrence:

let newpage = {
  page_no_3: {
    data1: [{index: 1, text: "test1"}],
    data2: [{index: 1, text: "test2"}],
  }
}

What I want to happen when I add new object:

let newpage = {
  page_no_3: {
    data1: [{index: 1, text: "test2"}, {index: 2, text: "test3"}, ...]
    data2: [{index: 1, text: "test2"}, {index: 2, text: "test4"}, ...]
  }
}

NOTE: Sorry it should not be an array but an object.

NOTE2: Sorry again. it should be Array with objects as elements.

PS: When I try to get the data of data1 before inserting, it is giving me an undefined error. I tried it like this:

let page_no = 'page_no_3'
if (nextpage.length == 0) {
    ///
} else { // Both undefined
    console.log(nextpage[page_no].data1)
    console.log(nextpage["page_no_3"].data1)
}

But if I only console.log(nextpage[page_no]) I can see the {index: 1, text: "test2"}.

10
  • data 1 has a space in it. Are you sure that's correct? Commented Jun 23, 2021 at 7:22
  • What do you mean by "add array1[2]1 in data 1? Do you want to convert data 1 into an array? Also, you cannot have spaces in keys in your object, unless you enclosed them in quotes. Commented Jun 23, 2021 at 7:22
  • 1
    Can you please show a real reference, the pseudo-reference is not accurate enough. Commented Jun 23, 2021 at 7:25
  • If I understand correctly what you want probably this newpage["page_no_3"].data1 = array1[2] works for you Commented Jun 23, 2021 at 7:29
  • sorry if I added a space in data and 1. no there are no spaces Commented Jun 23, 2021 at 7:31

1 Answer 1

0

First check that your array exist :

if(newpage["page_no_3"].data1 === undefined){
   newpage["page_no_3"].data1 = [];
}

Then you can add a new object to data1 :

newpage["page_no_3"].data1.push(myAwesomeObject);

maybe this can help you to understand the difference between arrays and objects

Sign up to request clarification or add additional context in comments.

3 Comments

Thank you for posting an answer. However, I did try newpage["page_no_3"].data1 and newpage[page_no].data1 but it is giving me a Cannot read property of undefined.
is newpage defined ? is newpage["page_no_3"] defined ? You need to define everything before using it, newpage and the properties you want to access (here "page_no_3")
yes. everything is defined before the if else here.

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.