Some elements in the Javascript variable list obj.names are null while others maintain values

I'm currently working on compiling a list from an array, but I've encountered an issue where some of the fields are null, causing the code to break and return:

obj.names is null

Below is the snippet of code that's causing the problem:

My Code

var data = {
  "people": [{
      "id": "32",
      "description": "some description",
      "archived": "",
      "new": 0,
      "names": [{
        "name": "name 1",
        "translations": null
      }, {
        "name": "name 2",
        "translations": null
      }],
    }, {
      "id": "56",
      "description": "some description",
      "archived": "",
      "new": 0,
      "names": [{
        "name": "name 3",
        "translations": null
      }, {
        "name": "name 4",
        "translations": null
      }],
    }, {
      "id": "99",
      "description": "some description",
      "archived": "",
      "new": 0,
      "names": null,
    },

  ]
};

var mainData = [data];
var namesList = [];

for (var i = 0; i < mainData[0].people.length; i++) {

  var obj = mainData[0].people[i];
  
  if(obj.names) {
    var nme = obj.names.name;
    namesList.push(nme);
  }
}

console.log(namesList); //This should have the list of names
<div id="container"></div>

JSFiddle Link

How can this issue be resolved?

Answer №1

labels is a list of elements, you must extract the label attribute from each element in the labels list.

Revise these statements

var lbl = obj.labels.label;
listOfLabels.push(lbl);

with

if( obj.labels )
{
   var lbl = obj.labels.map( function(item){
    return item.label; 
   });
   listOfLabels = listOfLabels.concat(lbl);
}

The map function is utilized to loop through the list and retrieve the label attribute of each element.

Answer №2

I find array methods like map, reduce, and forEach to be very useful.

When using these methods, the resulting code might look something like this:

// In this example, we are looping over the people array but creating a new array with all the names from the names array using reduce.
var namesList = data.people.reduce(function( resultArray, person ) {
    // Concatenate names from the names array to our result
    return resultArray.concat(
        // Check if the names array exists before mapping through it
        person.names && person.names.map(function( nameObj ) {
            return nameObj.name;
        }) || []
    );
}, []);

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

The underscore convention for defining members in Typescript allows for clear and concise

Let's talk about a class called Email class Email { private _from: string; private _to: Array<string>; private _subject: string; } When an email object is created, it will look something like this: { _from:'', _to:'&apo ...

Setting up the karma ng-html2js preprocessor to locate my templates within a specific folder

Currently, I am facing an issue where I need to set the templateUrl: "partials/my-directive.html" However, I find that I have to use templateUrl: "app/partials/my-directive.html for it to be loaded by Karma. This is how my folder structure looks like (fo ...

What is the best way to shrink or enlarge individual sections of the accordion?

Exploring AngularJs Accordions I'm struggling to understand how to control accordions in AngularJS. I have a step-by-step module set up as an accordion and I want to collapse one part while expanding another based on completion. Here is the accordion ...

Is there a way to simulate the parameters of a method callback from an external dependency in Nodejs

Imagine a scenario where I have the following structure: lib/modules/module1.js var m2 = require('module2'); module.exports = function(){ return { // ... get: function(cb){ m2.someMethod(params, function(error, ...

Creating a stand-alone NPM module for a Redux store to be used in a React application

Can the Redux Store be developed as a separate npm package for a React App and then imported into it? For instance: Assuming there is a fictional React Project named reactapp. A package called reactapp-reduxstore is created containing the Redux Store, al ...

Trigger the function when the keyboard event is deactivated

Is there a way to continuously run the top set interval whenever I lift my finger from the space key? When I try using the key up event, it only executes that function once. I'm not sure how to implement if/else logic when adding an event listener. se ...

Troubleshooting multiple element visibility problems with jQuery

Please take a look at the code snippet below. $(document).ready(function(){ $(".like-btn").hover(function() { var rowid = $(this).attr("data-rowid"); $(".reaction-box[data-rowid='" + rowid + "']").fadeIn(100, function() { $(".reaction ...

Next.js ensures that dynamic routes do not result in redirection to a 404 page

I am facing an issue with my Next.js project. I have a file named [pid].js and I also want to add a custom 404 page. However, when I place the 404.js file inside the /pages directory, it causes a problem. If I remove the [pid].js file, the 404 page works f ...

What is the best way to continuously run a series of setInterval() functions in a never-ending

I attempted to create a function that would post measurement A every 5 seconds for 10 times, followed by posting measurement B at random intervals. The goal was to have this function repeat indefinitely in order to simulate a fake agent. My initial code l ...

Creative Wrapping with EaselJS

Most canvas frameworks have a built-in feature for controlling word wrapping using maxWidth and maxHeight parameters. While setting the maxWidth in EaselJS is straightforward, is it possible to efficiently set a maxHeight for text as well? ...

Trouble with text not wrapping in p tag from Json data source in AngularJS

I am fetching data from a JSON file and also retrieving some text content, but the text does not support the p tag. Here is a screenshot for reference: https://i.sstatic.net/IETSy.png When we fetch the text content, it appears like this (with p tag): JS ...

What is the best method to retrieve a nested JSON property that is deeply embedded within

I am facing an issue with storing a HEX color code obtained from an API in a Vue.js app. The object app stores the color code, for example: const app = {"theme":"{\"color\":\"#186DFFF0\"}"}. However, when I try to access the color prope ...

collecting items and storing them in an array

I am attempting to gather all course codes that have a score below 40 into an array and then display it. However, when I use print_r($carry_over), nothing is returned! $carry_over = array(); while ($row8 = mysql_fetch_assoc($query8)) { if ($row8[&ap ...

What steps should I take to execute a task during input checkout?

Check out my code below: $(document).on('checkout', 'input', function(){ alert('input is not focused anymore'); }) <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script> <i ...

Is it possible to manipulate div elements with JavaScript while utilizing node.js?

It seems like I'm missing something obvious here, as I'm working with node.js and I have correctly linked a javascript file (alert("hello"); works). However, I can't seem to make any changes to the DOM. Here's a simple example: jade: ...

How can we verify that a state parameter in React is not undefined?

Greetings and thank you for your valuable time! I am currently immersed in a React and Flux tutorial that can be found at this link: React Flux Tutorial The challenge I'm encountering revolves around creating a new author. Whenever I attempt to inpu ...

Angular ng-bind is incorrectly displaying the value as 'object' instead of the intended value

I am working on an Angular app where I am retrieving data from a service in the following manner: angular.module('jsonService', ['ngResource']) .factory('MyService',function($http) { return { getItems: ...

Angular.js:10671 Uncaught TypeError: Cannot read property of undefined

I am currently in the process of learning Angular through a course, despite having limited experience with JavaScript. I have been struggling to make ng-class function properly and cannot figure out why I keep encountering the error mentioned in the title. ...

Experiencing issues on the live server as it appears that Bootstrap is not functioning properly

I am facing an issue with my website where it appears distorted when launched on a live server, despite working fine locally. It seems that the Bootstrap styles are not being applied correctly on the live server and I cannot figure out why. If anyone knows ...

Utilizing nested JSON data with React

Hey there! I've been working on adding more levels in Json pulled from Mongo, but I'm running into an issue with accessing elements that have multiple levels of nesting. It seems like it can't read the undefined property. Is there a limit t ...