What is the procedure for obtaining a list of items with the second item marked as "true"?

Can you please provide guidance on how to iterate through a list of addresses (address object) where the object has the property "def" set to true? Here is an example response from an API request:

{
  "status": true,
  "rspa": [
    {
      "address": "FB2A23D4-554E9",
      "def": false,
      "tk": false
    },
    {
      "address": "FA0EBFB496DA-C5465A8D",
      "def": true,
      "tk": false
    },
    {
      "address": "FA0434B496DA-C5465A8D",
      "def": true,
      "tk": false
    }
  ]
}

The initial approach I tried is as follows:

myArray = data.rspa
var addrs = myArray.map(function(elem){
   return elem.def === true ? elem.address : "";
   }).join(",");
   console.log(addrs);

However, this code returns all addresses, not just the ones where "def" is true. The output includes: FB2A23D4-554E9,FA0EBFB496DA-C5465A8D,FA0434B496DA-C5465A8D

Additionally, I attempted a different approach:

myArray = data.data.rspa
 var idToLookFor = true;
 var foundObject = myArray.filter(function(item) {
   return item.def === idToLookFor;
 })[0].address;
console.log(foundObject);

Unfortunately, this code leads to an error message: Uncaught TypeError: Cannot read properties of undefined (reading 'address')

Answer №1

filter and map serve different purposes, and what you really need is a combination of both. While using map may have "worked," the issue was that the results were not filtered. First, apply filter to narrow down the data, then use map to reshape it as desired. Lastly, join the elements together and output the final outcome.

(Moreover, remember to use true instead of 'true' for filtering, since using === with a string won't yield the intended result.)

var data = {
  "status": true,
  "rspa": [
    {
      "address": "FB2A23D4-554E9",
      "def": false,
      "tk": false
    },
    {
      "address": "FA0EBFB496DA-C5465A8D",
      "def": true,
      "tk": false
    },
    {
      "address": "FA0434B496DA-C5465A8D",
      "def": true,
      "tk": false
    }
  ]
};

var myArray = data.rspa;

var result = myArray.filter(function(item) {
  return item.def === true;
}).map(function(elem){
  return elem.address;
}).join(",");

console.log(result);


On a side note... In this scenario, there is no need for idToLookFor. If result.def is true, you can simply return that value from the filter function.

Answer №2

An error occurs when you fail to account for the scenario where def is not true

let targetItem = myArray.find((element) => {
  return element.def === true;
});
targetItem ? console.log(targetItem.address) : console.log("not found");

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

When a user clicks on a child element in ReactJS, the onclick event returns as undefined

I am experiencing an issue with my restaurants list component. While I have an onClick event set up for each list item, clicking on a child element of the list item does not trigger the expected response. When this occurs, nothing happens or I see an undef ...

Show additional links beneath the main homepage URL in search engine result pages

Seeking a way to optimize search engine results to display sub-links under the main homepage of a website. Attached is a screenshot illustrating the desired outcome when searching for a particular term. Appreciate any insights or solutions on achieving thi ...

Unable to retrieve an image from various sources

My setup includes an Express server with a designated folder for images. app.use(express.static("files")); When attempting to access an image from the "files" folder at localhost:3000/test, everything functions properly. However, when trying to ...

Transform HTML into PNG with Canvas2image, followed by the conversion of PNG into BMP

Is there a direct way to convert HTML to BMP? After searching online, it seems that there isn't a straightforward method. So, I decided to convert HTML to PNG using canvas JS and then use PHP to convert the file from PNG to BMP. I have a question abou ...

There are two different ways to set a hyperlink in HTML. One method is by using the href attribute, where you provide the URL inside the quotation marks. The other

While browsing, I stumbled upon this interesting piece of JavaScript code: onClick="self.location.href='http://stackoverflow.com/'" I incorporated this code into my website, and it seems to have the same effect as using the href attribute. Sin ...

Angular provides the capability to sort through data using various criteria

I have received an array of objects in a specific format from the server, which may contain more than 2 objects. [ {processId : 1, processName : "process1", country : "germany", companyCode:"IB" , companyHiringType:"FRE", masterClauses:[ {cl ...

Which is better for privacy: underscored prototype properties or encapsulated variables?

There's something that's been on my mind lately - it seems like people are aware of something that I'm not. Let's take a look at an example in FOSS (simplified below)... When creating a class in JavaScript, I personally prefer Crockford ...

How can I enhance this conversion function from an Array to an Object in JavaScript?

Looking to construct an object consisting of empty arrays using values as keys. const CATEGORIES = ['apple', 'banana', 'orange'] generateCategoryObject() === { apple: [], banana: [], orange: []} function generateCategoryO ...

passing a javascript variable to html

I am facing an issue with two files, filter.html and filter.js. The file filter.html contains a div with the id "test", while the file filter.js has a variable named "finishedHTML." My objective is to inject the content of "finishedHTML" into the test div ...

Dealing with AngularJS memory leaks caused by jQuery

How can I showcase a custom HTML on an AngularJS page using the given service? app.service('automaticFunctions', function ($timeout) { this.init = function initAutomaticFunctions(scope, $elem, attrs) { switch (scope.content.type) { ...

"Transforming Selections in Illustrator through Scripting: A Step-by-Step Guide

In Illustrator, I successfully used an ExtendScript Toolkit JavaScript code to select multiple elements like text, paths, and symbols across different layers. Now, I am looking to resize them uniformly and then reposition them together. While I can apply ...

Concealing a form after submission using JavaScript

After submitting the form, I am attempting to hide it and display a loading GIF. I've experimented with various methods, including changing ClassName to Id, but haven't had success. This is for a school project, and I've spent a significant ...

What is the best way to obtain the clicked ID when a user clicks on an element within

As a budding web developer, I've been working on a code snippet to dynamically load data into an iframe: $(document).ready(function () { function loadMaterials(type, query) { $.ajax({ type: 'GET', url: &ap ...

Organize a collection of items in AngularJS

Consider the following array: var members = [ {name: "john", team: 1}, {name: "kevin", team: 1}, {name: "rob", team: 2}, {name: "matt", team: 2}, {name: "clint", team: 3}, {name: "will", team: 3} ]; I want to create an unordered list for each ...

Getting the value of a hidden input field within a div by accessing the event.target that initiated the event in JavaScript

I am working with a set of li elements, each containing specific child elements structured like this: <li class="list"> <!--Parent--> <input type="hidden" id="id" value="3"> <!--Child 1--> <div class="cd-1">....</div ...

Refresh choices for the user interface selection menu

I've successfully mastered the art of redefining options for Webix ui.richselect/ui.combo. The technique involves: richselect.getList().clearAll(); richselect.getList().parse(options_data) Now, I'm facing a challenge with changing options fo ...

Unable to utilize a function within a mongoose schema

I encountered an issue while attempting to access the schema methods of a mongoose schema in TypeScript. Schema const userSchema: Schema<IUser> = new Schema( { name: { type: String, required: [true, "Name is required"], ...

Why does React-Perfect-Scrollbar not work properly when the height of an element is not specified in pixels?

Currently, I am developing a chat application with React 18 for its user interface. The app includes a sidebar that displays user profiles. To ensure the app fits within the browser window height, I've made the list of user profiles scrollable when n ...

Grouping object properties in a new array using Java Script

I'm currently learning Java script and attempting to merge an Array of objects based on certain properties of those objects. For instance, I have the following array which consists of objects with properties a, b, c, pet, and age. I aim to create a n ...

Avoiding memory leaks when using three.js with a large number of shapes

My code is devouring memory at an alarming rate and ultimately crashing. After some investigation, I've determined that the issue seems to be related to the torus generation/removal portion of the code. Despite efforts to manage the scene array and t ...