Utilizing conditional statements within the array.forEach method to select specific sub-objects within an array of objects

Need help troubleshooting an if statement inside a function that is called by a forEach array loop.

My array contains objects, with each object structured like this:

arrofobj = [   
{"thing_id":"1a", "val": 1, "Type": "Switch","ValType":{"0":"Open","1":"Closed"}},  
{"thing_id":"1b", "val": 72, "Type": "Sensor","ValType":{"0":"%"}}]

I want to check if the Type is a switch, and if true, I need to populate a new field in the objects of the array CatX:
- If it is a switch, I will use the val value to determine which ValType element to include in a new variable of the array arrofobj.
- If it is not a switch, I will use the arrofobj.ValType.0 value.

const getCat = function(){
    if(arrofobj.Type !== 'Switch') 
        arrofobj.ValType'.0' 
    } else {
        arrofobj.ValType.(arrofobj.val)
};

arrofobj.forEach(p => p.CatX = getCat() ); 

I'm having trouble with the lint not accepting the code, so I am unable to test it.

Answer №1

1) Ensure that you are using bracket notation to access properties as strings.

2) Make sure to close the brackets correctly in if/else statements.

3) Remember to return a value from within the getCat function in order to assign something to p.CatX.

4) Be sure to pass the object to getCat inside the loop.

const arrofobj = [   
  {"thing_id":"1a", "val": 1, "Type": "Switch","ValType":{"0":"Open","1":"Closed"}},  
  {"thing_id":"1b", "val": 72, "Type": "Sensor","ValType":{"0":"%"}}
];
const getCat = function( obj ){
    if(obj.Type !== 'Switch') {
        return obj.ValType[ '0' ]
    } else {
        return obj.ValType[ obj.val ];
    }
};

arrofobj.forEach(p => {
  p.CatX = getCat(p);
}); 

console.log( arrofobj );

Answer №2

Adding to Shilly's response:

1) If you're generating your own data instead of using a third-party source, consider standardizing the format of your object property keys in camelCase. This will make it easier to work with and reduce the likelihood of introducing bugs into your code.

2) Utilizing object destructuring assignment and a ternary operator can help minimize the code footprint.

const arrayOfObjects = [
  { id: '1a', val: 1, type: 'Switch', valType: { '0': 'Open', '1': 'Closed' } },
  { id: '1b', val: 72, type: 'Sensor', valType: { '0': '%' } }
];

function getCategory(obj) {

  // Destructure the properties from obj
  const { type, valType, val } = obj;

  // Use a ternary operator to determine what to return
  return type === 'Switch' ? valType[val] : valType['0'];
}

arrayOfObjects.forEach(obj => {
   obj.category = getCategory(obj);
});

console.log(arrayOfObjects);

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 can be done to ensure that the a href tag is functioning as clickable?

Having an issue with my HTML and CSS code for a notification dropdown box. I am unable to click the tag, even after attempting to use JavaScript. Can't seem to figure out what's causing this problem. Any advice on how to make the tag clickable? ...

What is the significance of using composability over the deprecated method in Reactjs Material-UI menuItems?

I have taken over a project that was built using an older version of react, and I am currently in the process of updating it. However, I encountered console errors right off the bat. Error : bundle.js:6263 Warning: The "menuItems" property of the "Left ...

Accessing the integer array's value using reflection

Currently, I am attempting to access the value of an int[] through reflection, but it has proven to be a challenging task. Below is the code I have been using: This is the specific value I am trying to retrieve: public int[] blah; for(Field f : c.getDec ...

Passing data from an API in Vue.js to a different page

I'm a beginner with Vue Js and I'm looking for guidance on how to send data between two components. Currently, I am working on a Vue app that fetches a list of users from an API and displays them. My goal is to transfer data between these compone ...

Can you please identify the TypeScript type associated with the return value of the match() method in String prototype?

I need help with creating a Regex in JavaScript const pattern = /S(\d+)E(\d+)/; // identifying characters between "S" and "D" const result = 'SE01E09'.match(pattern); How should I declare the result variable? I have attempted various ...

When the draggable item is released near the drop zone, allow drag and drop to combine

In my latest project, I created a fun game that involves matching different shapes. The goal is to drag the correct figure next to its corresponding shadow figure for a perfect match. Currently, if you partially overlap the square with its shadow, the game ...

The issue arises when trying to apply Bootstrap CSS styles to dynamically created elements using JavaScript

I utilized JavaScript to create a Bootstrap Modal and followed the correct classes as outlined in the Bootstrap documentation, but unfortunately, the JavaScript-created elements are not being affected. Even after adding the Bootstrap classes and attribute ...

Endless AngularJS loop using ng-view

I recently started experimenting with AngularJS for a new project I am working on, but I have encountered a problem when dealing with routes and views. For the sake of simplicity, I have minimized this example to its basic form, yet the issue persists. Th ...

jQuery: Eliminating Parent Elements

Currently, I am developing a small web application that allows users to create lists which are then formatted and emailed to them. However, I am facing difficulties in implementing a method that will allow users to delete list items without clearing the en ...

Playing embedded YouTube videos automatically in Safari 11 without user interaction

I’m encountering an issue with a simple modal dialog: When a user clicks on a button, the modal overlay appears. An embedded YouTube <iframe> is then added. Everything works smoothly in most browsers, except for Safari 11.1. Safari’s new auto ...

What is the method for presenting text based on the chosen Select Option?

I attempted to achieve this using hrefs and ids, but it did not meet my requirements. This is the desired format: div.selectcountry { margin-bottom: 10px; font-family: arial; font-size: 12px; } div.countrydepartment { font-family: ...

The error message "Data type must be consistent across all series on a single axis in Google Chart" may cause confusion

I'm struggling with an error message that appears when I try to run my Google chart. Here is the code I am using to generate the chart. function (resultVal) { var arrMain = new Array();//[]; for (var i = 0; i < resultVal.length; i++) { ...

Manipulating the information pulled from an external PHP script that is currently being displayed

Although I don't consider myself a professional, I am determined to learn some web languages this summer to be able to turn my design ideas into prototypes. Currently, I am struggling to figure out how to manipulate elements that are being echoed bac ...

Pass the AngularJS object to a different MVC Controller when a button is clicked in the MVC view

When a button is clicked on the view, I need to pass an AngularJs object to another controller. CHTML <div ng-repeat="hotel in respData.hotels"> <button type="button" class="btn" data-ng-click="setTab(hotel.code)">Check Availability</bu ...

What could be the reason behind the failure of this computed property to update in my Vue 3 application?

As I transition from Vue's Options API to the Composition API, I decided to create a small Todo App for practice. Within App.vue, my code looks like this: <template> <div id="app"> <ErrorMessage v-if="!isVali ...

Could anyone assist me in resolving the error stating, "The 'Argument `where` of type UserWhereUniqueInput needs at least one of `id` arguments"?

Upon investigating, I inserted this console log to determine what data is being received: { username: 'aa', gender: 'Feminino', cargo: '2', email: 'a', password: 'a' } Lately, I've been facing this err ...

JavaScript AJAX function is returning an undefined value rather than a boolean true or false

My AJAX call function in jQuery has a complete section with the following code: complete: function(XMLHttpRequest, textStatus) { if(textStatus == "success") { return(true); } else { return(false); } } However, when ...

How can I ensure that the images span the entire width of the page in ResponsiveSlides?

I am trying to make my images occupy the entire width of the page just like in this example: However, I have not been able to find a property for this. I'm new to using Jquery but I have a good understanding of Javascript Can someone please help me ...

What could be causing my Apollo useLazyQuery to be triggered unexpectedly within a React hook?

import { useLazyQuery } from '@apollo/client'; import { useEffect, useState } from 'react'; import { ContestSessionResponseInfoObject, GetSessionDocument, HasAccessToRoundDocument, } from '@/graphql/generated/shikho-private- ...

Guide on Implementing Link href in Next.js v12

When I set the href as a string, the link functions properly. However, when I use an object for the href, the link fails to work. Despite seeing the correct querystring when hovering over the link, it always takes me back to the first page. // ProdCard t ...