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

What is the reason for the reconnect function not activating when manually reconnecting in Socket.IO?

After disconnecting the client from the node server using socket.disconnect(true);, I manually re-establish the connection on the client side with socket.open(). The issue arises when triggering socket.open(); the socket.on('reconnect', (attempt ...

Advantages of optimizing NodeJS/TypeScript application by bundling it with webpack

Currently, I am working on a Node/Express application and I am interested in incorporating the most recent technologies. This includes using TypeScript with node/Express along with webpack. I have a question: What advantages come with utilizing webpack t ...

How far apart are two surfaces when they are rotated along the Y-axis

Access Code: Click here to access the code I am trying to make sure that the red surface lies completely flat on top of the gray surface. However, there seems to be a gap (marked ??) between the two surfaces when I rotate 'modifier1'. How can I ...

The 'Subscription' type does not contain the properties _isScalar, source, operator, lift, and several others that are found in the 'Observable<any>' type

Looking to retrieve data from two APIs in Angular 8. I have created a resolver like this: export class AccessLevelResolve implements Resolve<any>{ constructor(private accessLevel: AccessLevelService) { } resolve(route: ActivatedRouteSnapshot, sta ...

Implement lazy loading of content on scroll in Grails framework

Currently, I am uploading images and displaying them in a gsp view. My goal now is to implement a functionality where the images load as I scroll down on the page. A friend suggested using jQuery to make an ajax call for this. Can someone please provide g ...

Having difficulty retrieving the current time of an audio element using jQuery

Currently, I am facing an issue while attempting to manage an audio element for my custom player. Despite numerous attempts, I have been unsuccessful in acquiring the currentTime and duration properties. Below is a snippet of what I've tried: var pla ...

Discover each *distinct arrangement* from a given array

I'm looking to generate unique combinations of element positions in a JavaScript array. Here's the array I am working with: var places = ['x', 'y', 'z']; The combinations I want are: [0,1], [0,2], [1,2]. Current ...

How do I add a "Switch to Desktop Site" link on a mobile site that redirects to the desktop version without redirecting back to the mobile version once it loads?

After creating a custom mobile skin for a website, I faced an issue with looping back to the mobile version when trying to add a "view desktop version" link. The code snippet below detects the screen size and redirects accordingly: <script type="text/j ...

Tips on navigating the scroller vertically as the user interacts with a selected div by scrolling up and down

On my webpage, I have various div elements displayed. Each div has the options to move it up or down using the buttons labeled "UP" and "Down". When a user selects a div, they can then use these buttons to adjust its position. I am looking for a way to au ...

Is There a Name Clash Issue with Dependency Injection in AngularJS?

Let's say I have two modules, finance2 and finance3, both of which define a service called currencyConverter. If I specify that my main module only depends on finance2, I can inject the service like this: angular.module('invoice2', [' ...

Over-extended Affix in Bootstrap 3.1.0

I'm currently using Bootstrap 3.1.0. The issue I've encountered is that when the "affix" becomes too long for the viewport, it ends up getting cut off and doesn't display the bottom items. Is there a way to make Bootstrap's affix featu ...

Can you clarify the concept of closures and how they bind the loop counter to the function scope?

I have observed programmers setting up event listeners inside loops, utilizing the counter. The syntax that I have come across is as follows: for(var i=0; i < someArray.length; i++){ someArray[i].onclick = (function(i){/* Some code using i */})(i); ...

Unable to find the module... designated for one of my packages

Within my codebase, I am utilizing a specific NPM package called my-dependency-package, which contains the module lib/utils/list-utils. Moreover, I have another package named my-package that relies on my-dependency-package. When attempting to build the pr ...

How do I fix the build error that says "Operator '+' cannot be used with types 'number[]'?

The function below is designed to generate unique uuidv4 strings. function uuidv4() { return ([1e7] + -1e3 + -4e3 + -8e3 + -1e11).replace(/[018]/g, c => ( c ^ (crypto.getRandomValues(new Uint8Array(1))[0] & (15 >> (c / 4)) ...

Is it possible to simultaneously verify if an array is empty within an Object along with checking the other fields?

Let's say I have an object that has the following structure: filter: { masterName: '', service:[], } What is the best way to determine if both the array and masterName field are empty? ...

Mastering the ng-submit directive for AngularJS

Having an issue with my form that submits a location to Google's Geocoder and updates the map with the lat/long. When using ng-click on the icon, it requires double clicking to work properly. And when using ng-submit on the form, it appends to the URL ...

Learn how to implement data-binding in AngularJS using the ui-router and ControllerAs syntax, all without the

I have been following the guidelines laid out by John Papa, but I am facing difficulty in binding values from child controllers to parent controllers using ui-router, ControllerAs, and vm variables instead of $scope. In my attempts, I created two example ...

Engaging Floor Layout

Currently, I am in the process of developing an interactive floorplan for an office project. The main objective is to provide a user-friendly interface where individuals can search for a specific employee and have their respective office location highlight ...

I'm having trouble getting the second controller to function properly in my AngularJS application

I've been looking everywhere for a solution on how to implement two controllers, but I can't seem to get it working. Could there be something wrong with my HTML or could the issue lie in my script? Here is the JavaScript code: <script> v ...

The Viadeo Social Toolbox seems to be encountering technical difficulties at the moment

I attempted to utilize a Viadeo Social Toolbox, specifically the Viadeo Share Button, but it seems to be malfunctioning in certain browsers? I came across some outdated viadeo share URLs like this: http://www.viadeo.com/shareit/share/?url=${url}&title ...