Choosing an element from an array in JavaScript that meets a certain criteria

How can I isolate an object from an array where the value for the "slug" key is "A"?

For instance, consider the following data:

 var allItems = [
    {
        "slug": "henk",
        "company_founded": "2008",
        "company_category": "Clean",
        "company_logo": false,
        "company_description": "",
    }
    {
        "id": "bas",
        "company_founded": "2012",
        "company_category": "Health",
        "company_logo": false,
        "company_description": "",
    }
    {
        "slug": "jan",
        "company_founded": "2005",
        "company_category": "Clean",
        "company_logo": false,
        "company_description": "",
    }
]

I aim to store the object with the slug value of "henk" in a new variable.

Thus, after extraction, I will be able to work with something similar to this:

var = SelectedItem = {
    "slug": "henk",
    "company_founded": "2012",
    "company_category": "Health",
    "company_logo": false,
    "company_description": "",
}

Appreciate your help!

Answer №1

To find the specific element you are looking for, iterate through your list and use a condition to select it:

let result;
for(const item of allItems) {
    if(item.company_founded === "2012") {
        result = item;
        break;
    }
}

Answer №2

If you're interested, I recommend checking out the documentation on Array.prototype.find:

 const targetItem = itemList.find(function(item){
     return item.slug === 'henk';
 });

Answer №3

If you have a scrambled object, one approach is to loop through all properties and filter out the objects that contain a specific value.

var allItems = [{ "slug": "henk", "company_founded": "2008", "company_category": "Clean", "company_logo": false, "company_description": "", }, { "id": "bas", "company_founded": "2012", "company_category": "Health", "company_logo": false, "company_description": "", }, { "slug": "jan", "company_founded": "2005", "company_category": "Clean", "company_logo": false, "company_description": "", }],
    result = allItems.filter(function (a) {
        return Object.keys(a).some(function (k) {
            return a[k] === 'henk';
        });
    });

document.write('<pre>' + JSON.stringify(result, 0, 4) + '</pre>');

Answer №4

Ensure consistency: Array containing objects (separated by commas, id changed to slug for uniformity.)

The assumption is that the property is unique OR it will fetch the LAST ONE in the sequence. Similar to an ID search or similar process.

MODIFIED to display value within a complex object rather than a simple array EDIT2: include a secondary lookup based on category

var allItems = {"fred":"H fred",rats:"rats",lookupitems: [{
  "slug": "henk",
  "company_founded": "2008",
  "company_category": "Clean",
  "company_logo": false,
  "company_description": "",
} ,{
  "slug": "bas",
  "company_founded": "2012",
  "company_category": "Health",
  "company_logo": false,
  "company_description": "",
}, {
  "slug": "jan",
  "company_founded": "2005",
  "company_category": "Clean",
  "company_logo": false,
  "company_description": "",
}]};

Create a reusable lookup mechanism:

var lookup = {};
var lookupbycategory = {};
// reference the above list and apply it consistently
lookup.list = allItems.lookupitems;
for (var i = 0, len = lookup.list.length; i < len; i++) {
  lookup[lookup.list[i].slug] = lookup.list[i];
  lookupbycategory[lookup.list[i].company_category] = lookup.list[i];
}

Retrieve one item (and use it)

var mychoice = lookup["henk"];
alert(JSON.stringify(mychoice));
alert(JSON.stringify(lookupbycategory["Clean"]));

Reutilize it

var mybas = lookup["bas"];

Answer №5

One possible approach is to store the data in an object with keys corresponding to specific identifiers. Here's an example:

var itemList = {
  "apple":
    {
        "type": apple,
        "color": "red",
        "taste": "sweet",
        "ripe": true,
        "description": "",
    },
  "banana":
    {
        "type": banana,
        "color": "yellow",
        "taste": "creamy",
        "ripe": true,
        "description": "",
    }
]

This structure allows for quick retrieval of a value like itemList.apple

Using this method results in faster indexing due to logarithmic hash-table lookup instead of linear iteration.

----- edit ----

To optimize lookups, you can preprocess the data by creating a new structure if the cost of generating it is lower than the cost of repeated lookups. For instance:

var itemListByKey = {}
for(var i = 0, l = itemList.length; i<l; i++){
   var item = itemList[i];
   itemListByKey[item.type] = item;
}

Now, itemListByKey will have a similar structure as shown earlier

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

Issue with AngularJS: Copying and appending with $compile is not functioning properly

Below is the snippet of my angularjs Controller var $tr = angular.element("#parent" + obj.field_id).find("tbody"), $nlast = $tr.find("tr:last"), $clone = angular.copy($nlast); $clone.find(':text').val('' ...

Looking to add some random circle markers to your SVG map?

I currently have a single marker displayed on an SVG Map. My goal is to scatter markers randomly across the map within the path itself. I would greatly appreciate some assistance in implementing this feature. svg { border: 1px solid; overflow: visib ...

What is the best way to access a video stored in a local file on the initial page and then watch it on the subsequent

I recently encountered a scenario where I needed to select a video on one page and have it automatically play on another page without any redirection. The initial page displays a list of videos for selection, like this: FirstPage Once a video is chosen on ...

React app version displaying incorrect links to CSS and JS files

I have been immersed in a React project called Simple-portfolio, you can find the GitHub repository here: https://github.com/Devang47/simple-portfolio and the live site at this URL: While everything works smoothly on the development server, I encountered ...

Adjusting Classes in JavaScript with jQuery

I need to create a feature that changes the state of a button from active to inactive based on user input, using Bootstrap. Ultimately, I am working towards finding an intuitive way to validate form input so that the submit button can be pressed for PHP pr ...

Transform a string to a JsonArray with the help of the Gson library

I am seeking help to convert a linear String in MySQL into a Gson JsonArray. To summarize: "{\"name\":\"john\",\"age\":22,\"class\":\"mca\"}" -> {"name":"john","age":22,"class":"mca"} (Converted to Js ...

Transfer the information from the Data table into the Dictionary

public static Dictionary<string, object> ConvertDataTableToDictionary() { string sql = "SELECT Marks,Id FROM table4"; using (SqlConnection Connection = new SqlConnection((@"DataSource"))) { ...

Is it possible to utilize WebAssembly in JavaScript to access the memory of a C struct directly?

Looking at the C code snippet below, there is a struct defined as follows typedef struct { ValueType type; union { bool boolean; double number; Obj* obj; } as; } Value; The ValueType enum used in the struct is defined a ...

Embracing Error Handling with ES6 Promises

I am seeking clarification on how errors travel through a series of then continuations to a catch continuation. Consider the following code: Promise.reject(new Error("some error")) .then(v => v + 5) .then(v => v + 15) .catch(er ...

Creating a series of spots arranged in a semi-transparent line using JavaScript for a unique canvas

My attempt at creating a highlighter is encountering issues with transparency The problem might be due to using lineCap=round, resulting in multiple dark spots appearing in a single line (which shouldn't happen). It's difficult to fully describe ...

Inhibit the ASP:dropdownlist when the value of another ASP:Dropdownlist is selected

Trying to modify two asp.net dropdownlists using client-side JavaScript is my current challenge. Specifically, these dropdowns are located within a modal that opens with a function. The objective is to disable the second dropdown (dropdown2) whenever the ...

Accessing Google authentication: A guide to programmatically prompting user consent and retrieving the CredentialResponse after successful login

Is there a way to trigger the Prompt for User Consent to open when clicking a custom HTML button instead of the Login iframe button rendered by Google? I am utilizing the Sign In With Google JavaScript API, and while I couldn't find a function to achi ...

There seems to be a problem with how the navbar is being displayed in ResponsiveSlides.js

I am currently using WordPress, but I have come here seeking help with a jQuery/CSS issue. I am utilizing responsiveSlides.js to create a simple slideshow, however, when viewing it here at gallery link, it appears that something is not quite right. STEPS: ...

Setting the current time in an Animation using ThreeJS

I'm utilizing skinning and skeletal animation within ThreeJS. My goal is to navigate through an animation by moving backward and forward, as well as jumping to specific locations within the sequence instead of the usual looping behavior. The animatio ...

Unable to parse JSON data from a file in PHP

Having some issues with the json_decode function in PHP: Here's what my file contains: {1: ['oi','oi'], 2: ['foo','bar']} And here is the PHP code I am using: <?php $contents = file_get_contents("qui ...

Make this array output from PHP easier to understand by simplifying it

I'm facing difficulties with the formatting of my JSON data. Here is the structure of my script: $array1 = array(); for($i = 0; $i < 2 ; $i++) { $array1[] = array ( "stocks" => array ( "0" => "apple", "1" => "banana", ...

Utilize Express.js to seamlessly stream and process uploaded files with formidable and gm, ensuring a streamlined process without

I am looking for a solution to upload and resize an image in one step without having to write to disk twice. For uploading images, I am using: node-formidable: https://github.com/felixge/node-formidable And for resizing the images, I am using: gm: Howev ...

Struggling with integrating Appbar and Drawer components in Material UI with ReactJS

I am attempting to create my first app using ReactJS and Material UI, but I am facing some challenges. My main goal is to display a left drawer when the button on the bar is clicked. Here is the code I currently have in my App.jsx file: import React from ...

Are we retrieving multiple APIs the right way?

Looking for some guidance on fetching two APIs in React. I have created two functions to handle this task and called them simultaneously within another function. Should I stick with this approach or move the API calls to componentDidMount? Additionally, I& ...

Obtain data in JSON format through an xmlhttp request

I originally used jQuery for this task, but I now want to switch to regular JavaScript as I'll be incorporating it into phonegap. I aim to avoid relying on different JS frameworks every time I make a server request, which could potentially improve per ...