Retrieving Values from Array with AngularJS Keys - A How-To Guide

I need to access a specific value from a key inside an array, like this:

   $scope.result = [
{

    "key":"logo_big",
    "value":"/assets/images/aaa.jpg"
    },
    {
    "key":"logo_small",
    "value":"/assets/images/logo94x57Bis.png"
    },
    {
    "key":"project_name",
    "value":"Company"
    },
    {
    "key":"support_email",
    "value":"<a href="/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="5337362513343e323a3f7d303c3e">[email protected]</a>"
    }
    ];

How can I retrieve the value of 'logo_big'?

$scope.result['logo_big'] 

This currently returns undefined.

Answer №2

One way to retrieve the element with a specific key from an array is by iterating through the array until you find the desired element.

If your system supports Array.find() method, you can use it for a more efficient solution:

var targetElement = $scope.result.find(function(item) {
    return item.key === 'logo_big';
});
return targetElement && targetElement.value;

Alternatively, you can resort to using filter as a workaround:

var targetElement = $scope.result.filter(function(item) {
    return item.key === 'logo_big';
})[0];
return targetElement && targetElement.value;

Answer №3

To access elements in an array of objects, you can use the following code snippet:

for (let index = 0; index < dataArray.length; index++) 
{
  if (dataArray[index]["property"] === "value") 
  {
    console.log("Value found!");
  } 
}

Answer №4

If you prefer to handle this in an angular-friendly manner, utilize angular.forEach and verify the object's key

angular.forEach($scope.result, function(obj) {
      if (obj.key == "logo_big") {
        $scope.resultObj = obj.value;
        alert($scope.resultObj);
      }

DEMO

var app = angular.module("app", []);
app.controller("listController", ["$scope", function($scope) {
  $scope.name = 'StackOverflow';
  $scope.result = [{
    "key": "logo_big",
    "value": "/assets/images/aaa.jpg"
  }, {
    "key": "logo_small",
    "value": "/assets/images/logo94x57Bis.png"
  }, {
    "key": "project_name",
    "value": "Company"
  }, {
    "key": "support_email",
    "value": "<a href="/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="6a0e0f1c2a0d070b030644090507">[email protected]</a>"
  }];

  angular.forEach($scope.result, function(obj) {
    if (obj.key == "logo_big") {
      $scope.resultObj = obj.value;
    }
  });

}]);
<!DOCTYPE html>
<html ng-app="app">

<head>
  <script src="https://code.angularjs.org/1.4.7/angular.js"></script>
  <link rel="stylesheet" href="style.css" />
  <script src="script.js"></script>
</head>

<body ng-controller="listController">
  <h3>Enter an ID</h3>
   <h1> {{resultObj}}</h1>
</body>

</html>

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

Creating visual representations of class, organization, flow, or state diagrams using Vega or Vega-lite

I'm struggling to find an example of a state, class, flow chart, or org chart diagram created with Vega. Are there any available online? Vega seems like the perfect tool for this type of visualization, although it may be a bit complex. Without a star ...

What steps do I need to take in order to ensure that when the word Hello is entered, the resulting output will display e:1, h:1, l:2, o:1

<!doctype HTML> <html> <body> <h3>Enter a string: </h3> <input id="myInput1" type="text"> <button onclick="count()">See output</button> //Click to see th ...

What is the best method for updating inner html with AJAX using the results obtained from json_encode?

If you need further clarification on how this works, feel free to check out this fiddle for a demonstration. In my setup, I have multiple DIVs each with a unique ID such as desk_85 (the number changes accordingly). <div class="desk_box_ver id="desk_8 ...

How can I attach a click event to the left border of a div using jQuery?

I am wondering about a div element <div id="preview"> </div> Can anyone suggest a method to attach a click event specifically to the left border of this div? Your help is greatly appreciated. ...

How can I solve a tridiagonal matrix using Python code?

Currently, I am tackling an issue involving tridiagonal matrices. I referenced the tridiagonal matrix algorithm on Wikipedia in order to implement a solution. However, I have encountered a roadblock and my solution remains incomplete. Feeling confused and ...

The browser prevented the script located at “http://127.0.0.1:5500/assets/platform.png” from loading due to an invalid MIME type of “image/png”

Sorry if this question seems repetitive, but despite extensive searching, I haven't been able to find a solution to my specific problem. I am currently working on developing a basic JavaScript game, but I'm facing challenges when it comes to impo ...

Develop a novel function

I am working on a new Order page where users can select a category, then a service, and fill out the quantity field for their order. I have an idea to create a function using @if and @else statements. In this function, I want to display the quantity fiel ...

Placing a div with position:absolute inside another div with position:absolute and turning them into position:fixed

HTML <div class="box1"></div> <div class="box2"> <div class="box3"></div> </div> CSS Properties of box1, box2 and box3 are: box1 { position: absolute; z-index: 100; background-color: rgba(39, 39, 39, 0.3) ...

Common mistakes made while working with decorators in Visual Studio Code

Having trouble compiling TypeScript to JavaScript when using decorators. A persistent error message I encounter is: app.ts:11:7 - error TS1219: Experimental support for decorators is a feature that is subject to change in a future release. Set the ' ...

Utilizing CSS-in-JS to eliminate arrow buttons from a TextField

I'm currently developing a webpage using React and Material-UI. One of the components I have is a TextField element, and I need to remove the arrow buttons that typically appear on number input fields. If I were utilizing CSS, I could easily achieve t ...

Manipulating JSON with ng-model in AngularJS

Let's say I have a simple JSON similar to this: { "Object 0": {} } I am trying to display it as a tree structure. This is the approach I am taking: <span>{{key}}</span> // Object 0 <span>{{value}}</span> // {} <ul> ...

List of string references

It is a known fact that C automatically inserts the NULL(\0) character at the end of a character array. However, it does not add the NULL character at the end of an Array of pointers to strings. For example: If I write char name[]={40,20,30,20,22,22 ...

Encountering an error message stating, "Unable to assign value to 'onclick' property"

Currently, I am at a beginner level in Javascript. While working on some exercises, I encountered an issue with the 'onclick' function as mentioned above. Despite going through other queries in this forum, I have not found a solution that works ...

Tips for correctly linking JS and CSS resources in Node.js/Express

I have a JavaScript file and a stylesheet that I am trying to link in order to use a cipher website that I created. Here is my File Path: website/ (contains app.js/html files and package json) website/public/css (contains CSS files) website/public/scri ...

Selecting a event from Google Places Autocomplete using a mouse click

I have successfully implemented Google's autocomplete API as per the documentation. However, I am facing an issue with a form that is submitted via Ajax every time it changes. The problem arises when using the autocomplete feature for location selecti ...

Troubleshooting the issue of autoplay not functioning in HTML5 audio

I'm facing a strange issue with my code - the autoplay feature for audio is not working as expected. Typically, whenever I insert this particular piece of code into a website, the music starts playing automatically. However, it seems to be malfunctio ...

Should you make multiple API calls or just one?

Currently in the process of developing an application that combines NodeJS and VueJs. I have created an API endpoint that provides all the necessary data. For instance, it may include The top Football Team The bottom Football Team The team with the most ...

Irreparable Glitches in Mocha

While developing a blogging platform, everything ran smoothly when tested on a web server. However, I encountered some issues when trying to write unit tests using Mocha and Should.js. Surprisingly, errors kept popping up where they shouldn't have bee ...

How can you make a dynamic 360 image that responds to mouse movements using three.js?

Is it possible to achieve a three.js effect similar to the one shown here? We have come across solutions that involve drag&drop for camera angle control, but we are interested in having the mouse position dictate where the camera points. For instance, ...

Upgrading from ng-router to ui-router in the Angular-fullstack application

issue 1: url:/home, templateUrl: 'index.html is appearing twice. problem 2: views: templateUrl: 'views/partials/main.html is not visible at all. What am I doing wrong? How can I effectively incorporate ui-router into yeoman's angular-fulls ...