gw1500se Posted November 15, 2022 Share Posted November 15, 2022 I have an object that contains arrays and other elements. I need to add an array to that object but I cannot figure out how to do that. This is what I tried: json_array.push(excludes[]); Can someone give me the correct syntax? TIA. Quote Link to comment Share on other sites More sharing options...
maxxd Posted November 15, 2022 Share Posted November 15, 2022 Is json_array a JSON string or an array? Assuming it's an Array object, I'd say drop the square brackets from excludes (I'm assuming excludes is a valid Array object as well). Also, realize that Array.push() returns the resulting array, so if you're not assigning the return to anything you clearly won't see the updated values. Are you getting any errors in your console? What does the code around this look like? There's not really enough here to say with any certainty what issue(s) you're having. Quote Link to comment Share on other sites More sharing options...
gizmola Posted November 16, 2022 Share Posted November 16, 2022 the push method is for an array. Adding to objects can be done in a few ways: Using array syntax: obj['property'] Using "." notation: obj.property obj = { 'foo': ['apple', 'banana'], 'getFoo': function() { return this.foo } } console.log(obj.getFoo()) obj['bar'] = ['red', 'green'] obj.foobar = function() { return this.foo.concat(this.bar) } console.log(obj.bar) console.log(obj.foobar()) Example code in this codepen. Quote Link to comment Share on other sites More sharing options...
gw1500se Posted November 16, 2022 Author Share Posted November 16, 2022 To clarify, 'excludes' is not in the object (yes it is a json array/object) at this point but I want it to be an empty array for future use: json_array.excludes.push(<some string>); Quote Link to comment Share on other sites More sharing options...
Solution gizmola Posted November 16, 2022 Solution Share Posted November 16, 2022 1 hour ago, gw1500se said: To clarify, 'excludes' is not in the object (yes it is a json array/object) at this point but I want it to be an empty array for future use: json_array.excludes.push(<some string>); And everything I wrote previously still applies. let json_array = {} json_array.excludes = [] // Use array method json_array.excludes.push("a") json_array.excludes.push("b") //array syntax json_array["excludes"].push("c") console.log(json_array) I Updated the codepen as well with this example code. Quote Link to comment Share on other sites More sharing options...
gw1500se Posted November 16, 2022 Author Share Posted November 16, 2022 Thanks. That was what I was missing. Quote Link to comment Share on other sites More sharing options...
Recommended Posts
Join the conversation
You can post now and register later. If you have an account, sign in now to post with your account.