What is the best way to input information into an object?

I am having an issue where I am trying to add data into an object, but I keep getting the error "push is not a function".

Here is the object in question:

var item = {
  "_id": {
    "$oid": "asdf976"
  },
  "Categories": [{
    "mainmodels": [{
      "submodels": [{
          "price": "2000",
          "submodelname": "lumia021",
          "Remainingphones": "0",
          "Bookedphones": "0",
          "Numofphones": "10"
        }, {
          "price": "2000",
          "submodelname": "lumia341",
          "Remainingphones": "5",
          "Bookedphones": "5",
          "Numofphones": "10"
        }

      ],
      "Status": "Active",
      "modelname": "lumia",
      "fromdate": "2016-04-01T16:39:12.051Z",
      "todate": "2016-04-31T19:19:44.051Z"
    }],
    "brand": "nokia"
  }],
  "rank": "1",
  "name": "first"
}

I am trying to add the following data:

var modal = {
                'custid': '1',
                'packcode': '22'
            };
            item.push(modal);
            console.log(item);

This is what I am expecting the result to be:

var item = {
  "_id": {
    "$oid": "asdf976"
  },
  "Categories": [{
    "mainmodels": [{
      "submodels": [{
          "price": "2000",
          "submodelname": "lumia021",
          "Remainingphones": "0",
          "Bookedphones": "0",
          "Numofphones": "10"
        }, {
          "price": "2000",
          "submodelname": "lumia341",
          "Remainingphones": "5",
          "Bookedphones": "5",
          "Numofphones": "10"
        }

      ],
      "Status": "Active",
      "modelname": "lumia",
      "fromdate": "2016-04-01T16:39:12.051Z",
      "todate": "2016-04-31T19:19:44.051Z"
    }],
    "brand": "nokia"
  }],
  "rank": "1",
  "name": "first",
  'custid': '1',
  'packcode': '22'
};

Can anyone help me figure out how to achieve this?

Answer №1

Objects do not have a `push` method; only arrays do.

To achieve what you want, simply assign properties directly to the object like so:

item.custid = '1';
item.packcode = '22';

If separation is crucial, you can utilize `Object.assign` in ES2015:

var modal = {custid: '1', packcode: '22'};
Object.assign(item, modal);

However, in this scenario, maintaining a direct link between `modal` and `item` is not necessary.

Live Example:

var item = {
  "_id": {
    "$oid": "asdf976"
  },
  "Categories": [{
    "mainmodels": [{
      "submodels": [{
          "price": "2000",
          "submodelname": "lumia021",
          "Remainingphones": "0",
          "Bookedphones": "0",
          "Numofphones": "10"
        }, {
          "price": "2000",
          "submodelname": "lumia341",
          "Remainingphones": "5",
          "Bookedphones": "5",
          "Numofphones": "10"
        }

      ],
      "Status": "Active",
      "modelname": "lumia",
      "fromdate": "2016-04-01T16:39:12.051Z",
      "todate": "2016-04-31T19:19:44.051Z"
    }],
    "brand": "nokia"
  }],
  "rank": "1",
  "name": "first"
};
item.custid = '1';
item.packcode = '22';
// JSON used for illustration only
document.body.innerHTML =
  "<pre>" + JSON.stringify(item, null, 2) + "</pre>";

You can also achieve this with `Object.assign`:

var item = {
  "_id": {
    "$oid": "asdf976"
  },
  "Categories": [{
    "mainmodels": [{
      "submodels": [{
          "price": "2000",
          "submodelname": "lumia021",
          "Remainingphones": "0",
          "Bookedphones": "0",
          "Numofphones": "10"
        }, {
          "price": "2000",
          "submodelname": "lumia341",
          "Remainingphones": "5",
          "Bookedphones": "5",
          "Numofphones": "10"
        }

      ],
      "Status": "Active",
      "modelname": "lumia",
      "fromdate": "2016-04-01T16:39:12.051Z",
      "todate": "2016-04-31T19:19:44.051Z"
    }],
    "brand": "nokia"
  }],
  "rank": "1",
  "name": "first"
};
var modal = {
  custid: '1',
  packcode: '22'
};
Object.assign(item, modal);
// JSON used for illustration only
document.body.innerHTML =
  "<pre>" + JSON.stringify(item, null, 2) + "</pre>";

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Utilize webpack to import functions from separate files

I am looking to streamline the process of importing and using functions from a different file. Ideally, I would like to simply call these functions by their name without any extra prefixes or naming conventions. However, I am aware that using eval() can po ...

What is the best method to make a hyperlink within an IFrame open in a new window?

Let me share the code I've been working on: <!DOCTYPE html> <html> <head> <base target="_blank"> </head> <body> <div style="border: 2px solid #D5CC5A; overflow: hidden; margin: 15px auto; max-width: 800px; ...

The functionality of a switch statement relies on the presence of a React-Router

Is there a way to dynamically change the text in a paragraph based on which Route is currently enabled? I tried using a switch statement, but I'm unsure of how to implement it. Any suggestions or ideas? import React from 'react'; import &ap ...

jQuery Soundboard - Pressing a single button will automatically deactivate all other buttons

I am currently developing a unique jQuery/PHP soundboard feature where I am faced with the challenge of stopping the HTML5 Audio playback when clicking on just one button, while attached to several other buttons. Here is what I have managed to code so far: ...

Implementing ajax functionality for a form component in vuejs

I am currently working with a Vue.js component that serves as a form with a single field for an email input. The default value of this field, "email", is provided to the component by the parent as a prop. Upon form submission, I need to trigger an event to ...

Is it possible to utilize relative paths with webpack dev server in React JS projects?

While running the development server on localhost:3000 using npm run start, everything functions as expected. I am utilizing react-scripts and have not ejected the react app. Currently, my goal is to configure the dev server behind a reverse proxy so that ...

Is it possible to adjust the timezone settings on my GraphQL timestamp data?

I've come across a lot of helpful information regarding the usage of Date() and timezones, but something seems to be off. In my GraphQL setup (sourcing from Sanity), I have configured it to use formatString in this manner: export default function Minu ...

Exploring Sencha Touch: Unveiling the Inner Elements of Nested JSON Structures

Hello everyone, I am facing a challenge with Sencha Touch and could really use some assistance. My goal is to display a list of children's text using the JSON data provided below along with my Sencha Touch code snippet. While I have explored the API a ...

Newbie mishap: Utilizing an array retrieved from a function in javascript/jquery

After submitting the form, I call a function called getPosts and pass a variable str through it. My aim is to retrieve the data returned from the function. // Triggered upon form submission $('form#getSome').submit(function(){ var str = $("f ...

Just built a React App including a blog functionality, but for some reason the blog posts are not showing up. Any suggestions on how to fix this issue

I'm currently working on a project that involves creating a blog page for our react app. Despite my efforts, I am facing difficulty in getting the blog posts to show up. In order to retrieve all the posts from my MYSQL database, I have set up an API ...

How can I make the element.setAttribute() method function properly in Internet Explorer?

I am using JavaScript to set the style attribute of a text element with the element.setAttribute() method, giving it a name of "style" and a value of "my modifications to the style of text." While this method works well in most browsers, it is not functio ...

When utilizing the multipart/form-data content type in a form, the files being sent are transmitted as blank

I am currently developing a VueJS component that functions as a form to collect user information and enable multiple image uploads. The form is set with enctype="multipart/form-data" and exhibits the following structure : <template> <div> ...

Creating a dynamic path to an imported file in React: A step-by-step guide

Struggling with a dilemma regarding dynamically generated paths for importing files in React. I have utilized the map() function to generate a dynamic part of the code, consisting of a repetitive sequence of div elements, each housing an audio element. The ...

What's the best way to convert static data from JSON files within the Django framework?

I am dealing with a json file that contains an extensive list of geographic locations [ { "id": 1, "name": "Afghanistan", "iso3": "AFG", "iso2": "AF", ...

Place the elements of the array on individual rows

Here, I am successfully inserting dynamic array values into a database table. However, I need to make a slight modification to the code. Currently, the data is being inserted into the database table with commas separating the values. I would like each arra ...

Tips for utilizing the track OrbitControls in three.js

Presently, there are two blocks visible within the space: const material1 = new THREE.MeshBasicMaterial({color: '#00ff00'}); const cube1 = new THREE.Mesh(geometry, material1); cube1.position.set(0, 0, 0); const material2 = new THREE.MeshBasicMat ...

Performing a periodic sum on an array using Java 8 streams

I am looking to calculate a periodic sum on an array by summing values based on index modulo n. int size=100; double[] doubleArr = new double[size]; for (int i = 0; i < size; i++){ doubleArr[i]=Math.random(); } int n=2; double[] results= new double ...

Having trouble establishing a connection between Node.js and a MongoDB Cloud server

I'm encountering some issues trying to access MongoDB Atlas. The database name on MongoDB cloud is star and the collection name is clc. But unfortunately, I keep getting a "Cannot read property of null" error message. const MongoClient = require(&apo ...

Combine and calculate the total of several columns using the Loadash library

In my Vue application, I am faced with the challenge of grouping an array by date and then calculating sums for multiple columns. The current method I have only allows me to group and sum one column: receiptsByDate: function(){ let byDate = _.groupBy(t ...

Guide to setting a generic key restriction on a function parameter

Today, I decided to have some coding fun and try creating a generic pushUnique function. This function is designed to check if a new object being added to an array is unique based on a key, and then push it if it meets the criteria. At this point, all I h ...