Access specific object in array in Angular using its unique identifier

There is an array presented below:

this.questions = [
      {id: 1, question: "Do you feel a connection to a higher source and have a sense of comfort knowing that you are part of something greater than yourself?", category: "Spiritual", subs: []},
      {id: 2, question: "Do you feel you are free of unhealthy behavior that impacts your overall well-being?", category: "Habits", subs: []},
      {id: 3, question: "Do you feel you have healthy and fulfilling relationships?", category: "Relationships", subs: []},
      {id: 4, question: "Do you feel you have a sense of purpose and that you have a positive outlook about yourself and life?", category: "Emotional Well-being", subs: []},
      {id: 5, question: "Do you feel you have a healthy diet and that you are fueling your body for optimal health? ", category: "Eating Habits ", subs: []},
      {id: 6, question: "Do you feel that you get enough rest and that your stress level is healthy?", category: "Relaxation ", subs: []},
      {id: 7, question: "Do you feel you get enough physical activity for optimal health?", category: "Exercise ", subs: []},
      {id: 8, question: "Do you feel you practice self-care and go to the doctor regularly?", category: "Medical Maintenance", subs: []},
      {id: 9, question: "Do you feel satisfied with your income and economic stability?", category: "Financial", subs: []},
      {id: 10, question: "Do you feel you do fun things and laugh enough in your life?", category: "Play", subs: []},
      {id: 11, question: "Do you feel you have a healthy sense of balance in this area of your life?", category: "Work-life Balance", subs: []},
      {id: 12, question: "Do you feel a sense of peace and contentment  in your home? ", category: "Home Environment", subs: []},
      {id: 13, question: "Do you feel that you are challenged and growing as a person?", category: "Intellectual Wellbeing", subs: []},
      {id: 14, question: "Do you feel content with what you see when you look in the mirror?", category: "Self-image", subs: []},
      {id: 15, question: "Do you feel engaged at work and a sense of fulfillment with your job?", category: "Work Satisfaction", subs: []}

    ];

Another function exists:

getDimensions(id) {    
   //require logic for obtaining object from questions array by ID.      
}

In order to obtain the correct object based on ID from the array, how can I construct a map?

Answer №1

To solve this problem, you have the option to utilize .filter() or .find(). The key distinction lies in the fact that filter will loop through all elements and return those that meet the condition as an array, whereas find will only return the first matching element before stopping the iteration.

For example:

var questions = [
      {id: 1, question: "Do you feel a connection to a higher source and have a sense of comfort knowing that you are part of something greater than yourself?", category: "Spiritual", subs: []},
      {id: 2, question: "Do you feel you are free of unhealthy behavior that impacts your overall well-being?", category: "Habits", subs: []},
      ...
];

function getDimensionsByFilter(id){
  return questions.filter(x => x.id === id);
}

function getDimensionsByFind(id){
  return questions.find(x => x.id === id);
}

var test = getDimensionsByFilter(10);
console.log(test);

test = getDimensionsByFind(10);
console.log(test);

Answer №2

retrieveSize(ident) {
    let element = data.filter(value => {
        return value.ident == ident;
    });

    return element;   
}

Answer №3

CASE STUDY 1

By utilizing the array.filter() method, we can retrieve an array of objects that meet our specified condition.
Take a look at the demonstration below:

var data = [
      {id: 1, name: "Alice", age: 25},
      {id: 2, name: "Bob", age: 30},
      {id: 3, name: "Charlie", age: 35}
];

function filterData(){
  console.clear();
  var filter_criteria = document.getElementById("criteria").value;
  var filtered_array = data.filter(x => x.age > filter_criteria);
  console.log(filtered_array);
}
button {
  background: #ff9900;
  color: black;
  border: none;
  border-radius: 5px;
  padding: 10px;
  cursor: pointer;
}

input {
  padding: 10px;
}
<div>
  <label for="criteria"></label>
  <input id="criteria" type="number" name="criteria" placeholder="Enter age criteria">
  <button onclick="filterData()">Filter Data</button>
</div>

CASE STUDY 2

With the assistance of array.find(), we can retrieve the first matching item from the array and terminate the search process.

var data = [
      {id: 1, name: "Alice", age: 25},
      {id: 2, name: "Bob", age: 30},
      {id: 3, name: "Charlie", age: 35}
];

function findData(){
  console.clear();
  var target_age = document.getElementById("age").value;
  var found_object = data.find(x => x.age == target_age);
  console.log(found_object);
}
button {
  background: #ff9900;
  color: black;
  border: none;
  border-radius: 5px;
  padding: 10px;
  cursor: pointer;
}

input {
  padding: 10px;
  width: 250px;
}
<div>
  <label for="age"></label>
  <input id="age" type="number" name="age" placeholder="Enter target age">
  <button onclick="findData()">Find Data</button>
</div>

Answer №4

// This TypeScript code snippet is used in Angular 4+ projects        
const viewArray = [
          {id: 1, question: "Do you have a connection to something greater than yourself and find comfort in it?", category: "Spiritual", subs: []},
          {id: 2, question: "Are you free of unhealthy habits that affect your well-being?", category: "Habits", subs: []},
          {id: 3, question: "Do you enjoy healthy and fulfilling relationships?", category: "Relationships", subs: []},
          {id: 4, question: "Do you feel purposeful and optimistic about yourself and life?", category: "Emotional Well-being", subs: []},
          {id: 5, question: "Is your diet healthy and nourishing for optimal health?", category: "Eating Habits ", subs: []},
          {id: 6, question: "Do you rest enough and manage stress effectively?", category: "Relaxation ", subs: []},
          {id: 7, question: "Are you physically active enough for good health?", category: "Exercise ", subs: []},
          {id: 8, question: "Do you prioritize self-care and regular medical check-ups?", category: "Medical Maintenance", subs: []},
          {id: 9, question: "Are you content with your income and financial stability?", category: "Financial", subs: []},
          {id: 10, question: "Do you engage in fun activities and laughter often?", category: "Play", subs: []},
          {id: 11, question: "Do you maintain a healthy work-life balance?", category: "Work-life Balance", subs: []},
          {id: 12, question: "Do you feel peaceful and satisfied in your home environment? ", category: "Home Environment", subs: []},
          {id: 13, question: "Do you feel challenged and growing intellectually?", category: "Intellectual Wellbeing", subs: []},
          {id: 14, question: "Are you content with how you perceive yourself in the mirror?", category: "Self-image", subs: []},
          {id: 15, question: "Do you find fulfillment and engagement in your job?", category: "Work Satisfaction", subs: []}
    ];

         const arrayObj = any;
         const objectData = any;

          for (let index = 0; index < this.viewArray.length; index++) {
              this.arrayObj = this.viewArray[index];
              this.arrayObj.filter((x) => {
                if (x.id === id) {
                  this.objectData = x;
                }
              });
              console.log('Json Object Data by ID ==> ', this.objectData);
            }
          };

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

How to sum the elements within an array using Objective-C

I developed a unique algorithm to retrieve the first and last two objects from an array and add them together. If the sums match, it returns 2. If not, it proceeds to check if the sum of the second and third objects equals the sum of the last two objects. ...

"Printed within the custom directive, the ng model value shows up as undefined

I am currently in the process of creating a custom directive that involves a simple template consisting of an input type textarea. I am assigning the ng-model to ngmodel and creating a link function where I am trying to capture the value of ngmodel. Howeve ...

Showing a loading overlay during an AJAX call on a JSP page

Hello there! I'm interested in adding a special effect to my JSP page's center when making an ajax call to load a dropdown menu. Can anyone help me with this? Thanks! ...

How can I display real-time streams from multiple IP cameras on an HTML page using Flask and Python?

I am currently dealing with a collection of cameras and the corresponding URLs in RTSP format. I managed to create a simple script that extracts the camera URL from the camera_config JSON file, but now I'm facing the challenge of embedding these video ...

Understanding ng-if in AngularJSAngularJS includes a useful directive called ng

After using angularJS, I found myself wondering how to effectively implement its if statement in a particular way. I hope that my example will help clarify my question. Here is the if statement I am working with: <div data-ng-if="book.Availability> ...

Exciting Funnel Design with Highcharts

As someone new to the world of Highcharts library, I am eager to create a horizontal funnel. I noticed there is an example of a vertical funnel on http://www.highcharts.com/demo/funnel but I couldn't find any options to make it appear horizontal. I&ap ...

What could be causing the sudden triggering of ngOnInit in Angular 4?

After sending a request to the server, ngOnInit() { this.service.get(1).subscribe((response) => { this.whenDateCurrent = new DateCustomDate(); }); } Within the same component, there is a method that retrieves this.whenDateCurrent: public getCurre ...

Guide to effectively testing a function in Angular that outputs a promise

I am trying to unit test a function inside a component that calls a service method with 3 arguments and returns a promise. I have written the necessary code in Angular using karma jasmine testing framework. Would appreciate some feedback on my implementati ...

Unresolved promise within a nested service in the then() method

I am facing an issue with a particular service that requires retrieving an access token followed by a User object. Once this process is complete, further UI actions need to be executed. The problem lies in the fact that the login().then() function is being ...

What is the method to extract a single user instead of a group of users?

I am attempting to transition from a list of users to displaying the profile of a single user on a separate page. My goal is to achieve this using routerLink and passing the specific user's id to the next page. Although the routing is functioning co ...

React - Clearing State data retrieved from axios request

I am currently facing an issue with resetting the state of an object in my users array upon clicking the delete button. Even after successfully removing the object from the database, the state does not update as intended. I have managed to verify the prese ...

Steps for formatting a query to JSON in a PostgreSQL field using PHP

Having trouble crafting a PHP query to fetch a json value from a postgresql database. The issue lies in the json WHERE clause of this simple query: select * from json_data where jsonfield ? 'roottag'; If I use PDO prepare: $query->prepare( ...

The swap feature in drag-and-drop does not have a defined function

I am currently developing a to-do app that utilizes drag and drop functionality to reorder items in the list. However, I have encountered an issue where swapping elements works perfectly for the first five elements but throws errors when dealing with the s ...

Is the recursive function caught in an endless loop?

I developed a recursive method to search for a key-value pair within a multi-dimensional array Recursive Function: public function find_key_recursive($haystack, $needle) { foreach($haystack as $key=>$value) { if(is_array($value)){ ...

Unable to retrieve the result in the form of a JSON dictionary

I am currently receiving the output as a JSON string using the code provided below. However, I actually need it to be in JSON dictionary format without any leading and trailing quotes. How can I achieve this? It appears to work if I uncomment line4, but n ...

Angular 2 and beyond: delivering a unified global service instance for sub-modules

Exploring how to create a comprehensive service that can be accessed from submodules within an angular 2+ application is key. While the traditional component hierarchy setup works well for this, understanding the process when dealing with multiple modules ...

Passing HttpClient from app.module to another module and then to a service in Angular

Currently, I am in the process of developing my own Angular NPM Package with the prefix "ngx-*". I have successfully compiled the package and am now integrating it into a new project by utilizing the npm link command. Within the service, there is a constr ...

Experimenting with axios.create() instance using jest

I have attempted multiple solutions for this task. I am trying to test an axios instance API call without using any libraries like jest-axios-mock, moaxios, or msw. I believe it is possible, as I have successfully tested simple axios calls (axios.get / axi ...

The error message "AngularJS addclass function not recognized" appeared when attempting to apply the

As a newcomer to AngularJS, I'm attempting to use the addclass function but encountering an error: addclass is not a function $scope.viewReport = function(ev,element) { window.location="#tab7"; $scope.tabact = document.getElemen ...

Creating a web layout or template using HTML

Currently in the process of developing a website, my goal is to construct html templates that include placeholders for injecting pages/content, menus, and other elements. While I admire AngularJS for its flexibility in achieving this, I fear it may be too ...