0

I am attempting to sort data into an appropriate category of array once parsed;

First lets initialize my Array like so.

const foo = {
    bar: {},
    bar2: {}
}

I am unable to utilize the .push prototype on the subarray build, for example.

foo.bar.push('foobar');

The error I will receive is

TypeError: Cannot read property 'push' of undefined

The array has been initialized using the first block of code.

I have also attempted to use the following and receive the same response from the console.

foo[0].push('foobar');

How could one push data to a subarray?

BONUS POINTS/PS. What is this kind of array called? Is this a subarray or multidimensional array or neither?

Thanks in advance.

4
  • What is this kind of array called? which kind? {} is an Object Commented Oct 15, 2019 at 9:16
  • {} = new Object() and [] = new Array() Commented Oct 15, 2019 at 9:16
  • @RenéDatenschutz no it's not, it's without the constructor call. Commented Oct 15, 2019 at 9:18
  • @AZ_ it's with the constructor, without is sugar w3schools.com/js/js_arrays.asp Commented Oct 15, 2019 at 9:27

3 Answers 3

2

What you are declaring is an object not array.

const foo = {
    bar: {},
    bar2: {}
}

In this case bar and bar2 both are objects and not array. And push is not available on object's prototype.

Use this to declare arrays inside object.

const foo = {
    bar: [],
    bar2: []
}
Sign up to request clarification or add additional context in comments.

2 Comments

You saved the day! and bonus points as well! This is an OBJECT not array
Glad I could help.
0

I would add to shubham-gupta response that if you want to push to foo you should declare it as an array as well:

const foo = [{
    bar: [],
    bar2: []
}]

2 Comments

then you can't do foo.bar.push('foobar');
Correct, you should use foo[0].bar.push('poteto')
0

Christopher, the error says what it says because, it is not possible to push an element into an object, but only an array.

Check this page out, which differentiate the two.

To set the value of a key inside an object you do: <your_object>.<your_key>= <your_value>;

To push an element into an array, you do: <your_array>.push(<your_element>);

Hence the bar elements inside foo should be arrays => [], not objects;

In your case here, you seem to be wanting to push the element "foobar" into the array bar inside of the object foo.

To do that, all you need to do is:

const foo = {
    bar: [],
    bar2: []
}
foo.bar.push('foobar');

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.