Creating a brand new array based on the conditions of an if statement

I have an array of objects and I need to search for objects with a specific property. Once found, I want to create a new array only containing those objects.

var firstArray = [...]

for (var i = 0; i < firstArray.length; i++) {
  if (firstArray[i].name == 'index.png') {
    // create secondArray here
  }
}

Any assistance on this matter would be greatly appreciated!

Answer №1

Applying a filter is the way to go.

let filteredArray = originalArray.filter(item => item.type === 'photo.png')

Answer №2

var initial = [{
  'name': 'X'
}, {
  'name': 'Y'
}, {
  'name': 'Z'
}]
var finalArray = [];

for (index in initial) {
  if (initial[index].name == 'X') {
    finalArray = initial[index];
    console.log(finalArray)
  }
}

Please review this code snippet.

Answer №3

You may utilize this method

let data = {'item1': 5, 'item2': 10};
let itemList = [{'item1': 5, 'item2': 10}, {'item3': 15, 'item4': 20}]
let searchTerm = 'item2';
for(let i=0; i<itemList.length; i++){
  for(let prop in itemList[i]){
    if(prop == searchTerm){
      // add your functionality here.
    console.log('property = ', prop, 'value = ', data[prop]);
    }
  }
}

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 are some more efficient methods for implementing page location detection with Angular directives?

My website currently features a navigation bar with 4 anchor links that direct users to different sections of the page. As you scroll down the page, the corresponding link on the nav bar lights up to signify your position on the site. Experience it yourse ...

Using the `ng-if` directive in Angular to check for the

I need to output data in JSON format using items. To display a single item, I utilize ng-repeat="item in items". Additionally, I can access the user object of the currently logged-in user with user. Every item has the ability to belong to multiple wishlis ...

Using Javascript and ExtJS to retrieve the Codemirror Editor using a textarea

Hello to the wonderful stackoverflow community, I recently incorporated a Codemirror Editor into my ExtJSProject like this: addCodeMirrorPanel: function() { this.getAixmFormarea().add(Ext.widget({ xtype: 'textarea', fieldLabe ...

variables that have been declared as jquery elements

What are the recommended practices for declaring jQuery DOM elements as variables? Is there any distinction between var div = $('div'); and var $div = $('div'); other than improved readability? Thank you ...

What is the process for installing fontawesome using npm?

I encountered an error while attempting to install that looks like the following: $ npm install --save @fortawesome/fontawesome-free npm WARN saveError ENOENT: no such file or directory, open 'C:\Users\Admin\Desktop\package.json&a ...

Utilizing boolean sorting in Swift once all other conditions are satisfied

I am trying to sort an array based on a specific condition. If after comparing three other conditions and they are the same, I want to check if a boolean value is true or false. If it's true, I want it to be sorted first. However, I am unsure how to d ...

The $http GET request is redirected to the incorrect URL, resulting in the search

Currently, I am in the process of developing a single page application and utilizing Angularjs v1.2.28 for this project. In order to retrieve data from the backend, I have implemented an HTTP GET request using the following code snippet. return { ...

Tips for transforming JSO into JSON data format

Here is an example: var info = [{"name":"john","age":"30"},{"name":"smith","age":"28"}] I am looking to convert the above json object to a format like this result: [{name:"john",age:30},{name:"smith",age:28}] Any suggestions on how to achieve this? ...

Executing JavaScript code using an HTML form submission

Greetings, I have implemented an HTML form on my website for user login using AJAX (jQuery), but I am encountering some issues. Below is the JavaScript code: function validateLoginDetails() { $('[name=loginUser]').click(function() { ...

Using JavaScript to Transmit URL

Imagine I have a URL similar to this: http://localhost:8000/intranet/users/view?user_id=8823 All I aim to achieve is to extract the value from the URL using JavaScript, specifically the user_id (which is 8823 in this instance), and transmit it through an ...

Monitoring individual elements of an array within an Angular service

Is there a way to monitor changes in an array element within a service? Let's consider the following scenario with CartController and ProductListService. Within the ProductListService, data is fetched as follows: /** * Fetch all the products in us ...

Updating the style sheet of a selected menu item on an ASP.NET master page

I created an asp.net master page with a menu setup like this: <menu id="menu"> <nav id="main_nav"> <ul id="menu-primary"> <li ><a href="./">Home</a></li> <li><a href="staff.aspx"& ...

Diving into Angular2 template forms: unraveling the mysteries of the reset function

After going through the template forms tutorial in Angular2, I'm facing a bit of confusion regarding the behavior of the native reset JavaScript function on Angular2 ngModel. While it's not explicitly clarified in the official documentation, my u ...

Adding together a pandas timestamp with an array filled with timedelta values

Given a start date and an array containing irregular sample values in days, I am looking to use them as the date index for a pandas series. For example: In [233]: date = pd.Timestamp('2015-10-17 08:00:00') Out[233]: Timestamp('2015-10-17 0 ...

What is the best way to duplicate elements while maintaining their event listeners?

I'm currently developing a chrome extension that aims to incorporate JavaScript encryption into Gmail for the convenience of me and my friends. While most of it is working smoothly, I've encountered an issue when trying to clone a button already ...

Ways to effortlessly activate an angular directive once the page has been fully loaded

I am facing an issue with a print directive that is triggered by the print="id" attribute within an <a></a> element. The button is contained in a modal that remains hidden from the user. I want the directive to execute as soon as the modal is l ...

Selenium WebDriver is encountering difficulty loading the list of followers on Instagram

I have been learning JavaScript, Node.js, and Selenium Web Driver as part of my educational journey. One of my projects involves developing a simple bot for Instagram using the Chrome web driver to emulate a browser. However, I encountered an issue when t ...

The functionality of localStorage seems to be dysfunctional in Nuxt js when running in SSR mode

I am encountering an issue while trying to add items to a cart using vuex. The console is showing an error and the products on the page are not displaying correctly. Can someone please guide me on how to resolve this problem? The error in the console is: c ...

Creating a personalized filter using radio buttons in AngularJS

Having multiple radio buttons, I aim to filter results retrieved from a web API based on the selected radio button. HTML <div class="row"> <div class="small-8 medium-9 large-10 columns"> <ul class="no-bullet"> &l ...

Maintain Open State of Toggle Drop Down Menu

Having an issue with the toggle down menu or list on my webpage. The problem is that the menu is constantly open (the #text_box) when the page loads. My intention was for it to be closed initially, and then open only when the user clicks on the 'Ope ...