Determine in a JSON array and add to an array object if the key is not found

I've got a JSON array like this:

  0: {Id: "1", name: "Adam", Address: "123", userId: "i98"}
  1: {Id: "2", name: "John", Address: "456"}

The second object in the array doesn't have a userId key.

How can I iterate through the array and add the userId key with a value of 0 if it's missing?

This is what I've attempted so far:

let jsonData = JSON.parse(JSON.stringify(userData));

 for (const obj of jsonData) {
    var hasId = false;
      let objId = obj.find((o, i) => {
         if (o.userId === "userId") {
          hasId = true;
        }
      });
      if (!hasId) {
         obj.push();
       }
    }

However, I'm getting an error:

obj.find is not a function

Any suggestions on how to fix this issue and properly add the key value to the array would be appreciated.

Answer №1

In your code snippet, the variable obj is an object and does not have a find method. To check if an object contains an array, you can simply use if( obj.userId )

To iterate over an array, you can utilize the forEach method.

let jsonData  = [{Id: "1", name: "Adam", Address: "123", userId: "i98"},{Id: "2", name: "John", Address: "456"}];

jsonData.forEach(o => {
  o.userId = o.userId || 0; //Set userId to 0 if it is undefined.
})

console.log(jsonData);

Answer №2

If you want to manipulate an array using JavaScript, one way is to utilize Array.prototype.map() and the

Object.prototype.hasOwnProperty()
method as shown in this example:

var jsonData = [{Id: "1", name: "Adam", Address: "123", userId: "i98"},{Id: "2", name: "John", Address: "456"}]

jsonData = jsonData.map(i => {
  if(!i.hasOwnProperty('userId'))
    i.userId = 0;
  return i;
});

console.log(jsonData);

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

Issues with Ajax arise once URL re-routing is activated

When loading content using AJAX and ASP.NET web-methods, the following code is used to trigger the Ajax request: var pageIndex = 1; var pageCount; $(window).scroll(function () { if ($(window).scrollTop() == $(document).height() - $(window).height()) ...

Tips for setting a specific date using angular-bootstrap-datetimepicker

It appears to be requiring you to select a specific time as well. I have gone through the documentation multiple times, but I can't figure out how to only pick a date. Check out this link for more information: ...

Obtaining connected information in AngularJS with Firebase

After reviewing the example found at the following link: I am curious to know if AngularFire can be used to retrieve and show relational data (referred to as sparks) in a similar manner? ...

Building an array of objects using a foreach loop

i am struggling to create an array of objects from two input groups, each group consists of 3 inputs with data-side attributes set to left or right every input has a class named "elm" and a data-pos attribute set to a, b, or c <input class="elm-left elm ...

The key up event in JQuery does not seem to be triggered when selecting the second option in the Select2 plugin's multi

Encountered an issue with the select2 plugin while trying to change the option list based on user input for the second multiple option. The first time I enter text in the multi-select field, the keyup event is triggered and an ajax function is called to b ...

Press the button in an HTML document to activate JavaScript

What could be the issue with my code? I have a button in HTML <a class="btn btn-warning btn-mini publish-btn" href="#" data-rowid="@computer.id" data-toggle="modal" data-target="#myModal">Outdated</a> and my modal <fieldset style="text-al ...

What are the ideal scenarios for implementing React.Fragments?

Today I discovered React Fragments and their benefits. I learned that fragments are more efficient by reducing the number of tree nodes and improving cleanliness in the inspector. However, is there still a need to use div tags as containers in React compo ...

Having issues with Json stringification and serializing arrays

Having an issue with Json when using serializeArray. An example of my HTML form: <form action="" method="post" name="myForm"> ID: <input type="text" name="id" /><br/> State (XX): <input type="text" name="state" /><br/> <p ...

The intersection observer is unable to track multiple references simultaneously

Hey there, I've been using a switch statement in my Next.js project to dynamically serve different components on a page. The switch statement processes a payload and determines which component to display based on that. These components are imported dy ...

Is there a way to randomly rearrange an array of objects when the page loads, then iterate over the rearranged array without triggering a console warning about "two children with the same key"?

When shuffling the array and mapping over it in my application, I am able to correctly display the shuffled data using translate3d for a slider effect. However, I keep receiving a growing list of console warnings: "Encountered two children with the s ...

Tips for escaping an infinite loop within the componentDidUpdate function in reactjs

Currently, I am working on creating dashboards using reactjs. I have successfully implemented 4 tabs or buttons for charts, but I am facing an issue when clicking on different dashboards that have the same chart in the same panel. The chart is not updating ...

Assign individual heights to multiple iFrames according to their content's height

Dealing with multiple iframes on a single page. Each iframe is sourced from my domain. The goal is to automatically calculate and set the height of each iframe on the page. The current code sets all iframe heights to match that of a specific iframe: fun ...

What are some ways to customize the default Head tag in Next.js?

After using create-next-app to create a basic page, I decided to style the index.js page. I added a navigation bar within the header and now I'm trying to customize it. I've been wondering if there's a way to style the custom Head tag in Ne ...

Utilizing AngularJS to display numerous charts on a single webpage

Currently, I am looking for a solution to display multiple charts on the same page. My goal is to showcase individual performance through each chart for different persons. After exploring Google Charts, I noticed that it requires unique "id" attributes w ...

Data loading issue with asp.net mvc Ajax

I am currently facing an issue while attempting to fetch data from the controller using ajax. Controller [HttpGet] public ActionResult GetServices() { var data = _bbdb.ListServices.Where(d => d.Status == true).ToList(); return Json(data, JsonR ...

Adjusting the font color when hovering over multiline text

I am currently in the process of coding a website for my job, and I am working on changing the text color when it is hovered over. However, there seems to be a break in my code causing the text not to highlight all at once. Any guidance or suggestions on h ...

Choosing an option from a dropdown menu using WebDriverJs

I am struggling to select a value from a dropdown box using WebDriverJS. Despite searching through the user guide, I have not been able to find a solution. https://code.google.com/p/selenium/wiki/WebDriverJs I even attempted to use methods documented f ...

Issue detected with XMLHttpRequest - "The requested resource does not have the 'Access-Control-Allow-Origin' header."

Currently, I am working on the frontend development of an application using Angular 2. My focus is on loading an image from a third-party site via XMLHttpRequest. The code I have implemented for this task is as follows: loadFile(fileUrl) { const ...

Enabling the use of jQuery with Angular instead of JQLite

According to the angular DOCS, if jQuery is available, angular.element is an alias for the jQuery function. If jQuery is not available, angular.element delegates to AngularJS's built-in subset of jQuery, known as "jQuery lite" or jqLite. In an attemp ...

When utilizing Angular 2, this message is triggered when a function is invoked from the Observable

One of my services is set up like this: @Injectable() export class DataService { constructor(protected url: string) { } private handleError(error: Response) { console.log(this.url); return Observable.throw(new AppError(error)); ...