What is the process for obtaining the final element in an array of objects when a particular character is present in the value of a key?

Given the following array:

arrOfOranges =
[{ "kerp": "thisThing", "time": "@ rocks 3"},
{ "kerp": "otherThing", "green": "blah"},
{ "kerp": "thisThing", "time": "(countriesToTheStart ^"},
{ "kerp": "anotherThing", "yellow": "row row"},
{ "kerp": "anotherThing", "yellow": "rigorous"},
{ "kerp": "thisThing", "time": ",,,,"}]

Each item in the array has the fixed structure:

[{kerp: ''}] that can be one of three values: thisThing, otherThing, or anotherThing. The second key for each object depends on the value of 'kerp'.

If kerp is 'thisThing', then the second key is 'time'. => { "kerp": "thisThing", "time": ""},

If kerp is 'otherThing', then the second key is 'green'. => { "kerp": "otherThing", "green": ""},

If kerp is 'anotherThing', then the second key is 'yellow'. => { "kerp": "anotherThing", "yellow": ""},

I am trying to extract the last item in the array with 'kerp': 'thisThing'. However, the value associated with the 'time' key must contain a letter.

In the given array, the last item has 'kerp': 'thisThing', but the 'time' does not contain a letter.

Therefore, I need to retrieve the item from arrOfOranges where it's the last item with kerp as thisThing and time containing letters in the value:

{"kerp": "thisThing", "time": "(countriesToTheStart ^"}

Here is my current approach:

if (arrOfOranges.filter(a=>a.kerp === "thisThing")) {
    // Checking if the time value contains any letters
    if(arrOfOranges.time.match(/[\w]+/g))  {
        return arrOfOranges.slice(-1)[0];
    }
}

However, this solution is not working as intended. How can I achieve the desired outcome?

Answer №1

To ensure proper filtering, make sure the check stays within the filter function.

const arrOfOranges = [
  { "kerp": "thisThing", "time": "@ rocks 3"},
  { "kerp": "otherThing", "green": "blah"},
  { "kerp": "thisThing", "time": "(countriesToTheStart ^"},
  { "kerp": "anotherThing", "yellow": "row row"},
  { "kerp": "anotherThing", "yellow": "rigorous"},
  { "kerp": "thisThing", "time": ",,,,"}
 ]

const result = arrOfOranges.filter(orange => orange.kerp === "thisThing" && orange.time.match(/[\w]+/g));

console.log(result);

Answer №2

To reverse the order of your arrOfOranges, you can utilize the .reverse() method and then apply the .find() function on the reversed array. The find method will identify and return the first object for which the provided callback returns true. In the example below, I have set it to return true when the time key contains a word character represented by \w and when the kerp key matches "thisThing". It is important to note that I used .slice() before invoking .reverse() to avoid directly altering the original arrOfOranges array:

const arrOfOranges = [{ "kerp": "thisThing", "time": "@ rocks 3"}, { "kerp": "otherThing", "green": "blah"}, { "kerp": "thisThing", "time": "(countriesToTheStart ^"}, { "kerp": "anotherThing", "yellow": "row row"}, { "kerp": "anotherThing", "yellow": "rigorous"}, { "kerp": "thisThing", "time": ",,,,"];

const search = {kerp: "thisThing", key: "time"};
const res = arrOfOranges.slice().reverse().find(
  obj => obj.kerp === search.kerp && /\w/.test(obj[search.key])
);

console.log(res);

If you prefer a slightly more efficient method, you can opt for a traditional for loop that iterates backwards through the array:

const arrOfOranges = [{ "kerp": "thisThing", "time": "@ rocks 3"}, { "kerp": "otherThing", "green": "blah"}, { "kerp": "thisThing", "time": "(countriesToTheStart ^"}, { "kerp": "anotherThing", "yellow": "row row"}, { "kerp": "anotherThing", "yellow": "rigorous"}, { "kerp": "thisThing", "time": ",,,,"];

const search = {kerp: "thisThing", key: "time"};
function findObj(data, search) {
  for(let i = data.length-1; i >= 0; i--) {
    const curr = data[i];
    if(curr.kerp === search.kerp && /\w/.test(curr[search.key]))
      return curr;
  }
}

console.log(findObj(arrOfOranges, search));

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 can you ensure an element's height matches its width within an Ionic framework?

I am currently creating an application using the Ionic framework, and I am looking to set a square image as the background. The challenge is to ensure that the image scales appropriately for different screen resolutions; ideally, it should occupy the full ...

Concealing Website Elements with javascript based on class assignments

Despite my hesitation, I have to ask this question after unsuccessful searches in related articles. In my code, I have 7 nav links all with the same class. Due to the length of the HTML, I am looking for a way to hide contents until the link is clicked, an ...

Activating a link click inside a table with jquery

I have been attempting to trigger a click on an anchor within the table compareTable with the code below, however it does not appear to be working as expected. Would anyone be able to provide insight into a possible solution? $('#compareTable a' ...

Implementing a color change for icons in React upon onClick event

export default function Post({post}) { const [like,setLike] = useState(post.like) const [islike,setIslike] = useState(false) const handler=()=>{ setLike(islike? like-1:like+1 ) setIslike(!islike) } return ( <> <div classNam ...

Console is displaying an error message stating that the $http.post function is returning

Just diving into angular and I've set up a controller to fetch data from a factory that's loaded with an $http.get method connecting to a RESTful API: videoModule.factory('myFactory', function($http){ var factory = {}; facto ...

Share an image on Facebook using JSON structure on an Android device

I am looking to share an image on Facebook along with a JSON string. Currently, I have hardcoded the image in the string and it is working fine. However, I would like to know how to add a dynamic image instead. Below is the code snippet: parameters.putSt ...

Issues encountered when attempting to append the array objects to HTML using $.getjson

Hello, I have a JSON data structure as shown below: [{ "menu": "File", }, { "menu": "File1", }] I have created jQuery code to dynamically add the response to my HTML page like this: $(document).ready(function () { $.getJSON('data.json&a ...

Exporting methods/functions in React Native

import { width as responsiveHeight } from "react-native-responsive-dimensions"; I am trying to export responsiveHeight with the name width. Can someone please guide me on the correct way to do this? The current approach is not yielding any results. ...

Issue with Moment.js: inability to append hours and minutes to a designated time

I have a starting time and I need to add an ending time to it. For example: start=19:09 end=00:51 // 0 hours and 51 minutes I want to add the 51 minutes to the 19:09 to make it 20:00. I've attempted several different methods as shown below, but none ...

Merging data from different columns in a table to form a JSON structure

I have a database set up in athena that contains the following information: type state city zipcode ------------------------------- hot az phx 85281 hot tx dal 12345 cool wa sea 67890 cool ny nyc 67856 My g ...

Flipping json stringify safety

In my NextJS React application, I encountered an issue with circular references when using getInitialProps to fetch data. Due to the serialization method used by NextJS involving JSON.stringify, it resulted in throwing an error related to circular structur ...

Looping over the results of JSON.Parse() in Ruby on Rails can be done

I am new to using Rails but I am really enjoying it. However, I have encountered a problem that I can't seem to solve. Most of the solutions I find online are related to ActiveRecord objects, but my issue involves working with JSON data from a RESTful ...

I am looking to enhance the readability of my asynchronous function calls

At the moment, I am handling my Promises by calling an async function and then chaining it with .then(). But I feel like there could be a more readable approach. This is how it currently works: const fetchData = async() => { const response = await ax ...

Transferring multiple sets of data from Firestore to another collection proves to be ineffective

Currently, I have four separate collections stored in my firestore database: EnglishQuestions MathQuestions ScienceQuestions DzongkhaQuestions My goal is to consolidate all the data from these individual collections and organize it under one collection f ...

Looking for assistance with parsing C# / .NET 6 into individual objects

I am currently working with the JsonSerializer.Deserialize() method from the System.Text.JSON library in .NET 6. The JSON format is beyond my control. While I have successfully used this method before, the data I'm dealing with now is slightly more ...

Transform a dictionary of bytes into JSON format

I've encountered an issue trying to convert a bytes dictionary returned from an API into JSON format, but so far I haven't been successful. Here is a snippet of the sample data: >>> endpoint_req.content b'{\n "ERSEndPoint" : ...

Error: The function **now.toUTCString** is not recognized and cannot be executed by HTMLButtonElement

While the JavaScript code runs smoothly without setting a time zone, I encountered an error when trying to display the Barbados time zone. The issue is related to now.toUTCString function throwing the following error message. How can I resolve this? Uncau ...

Determine the height of the left div, which is set to auto, and apply the same height to the right div, which has overflow set

I am facing an issue that needs a solution. I need to ensure that two div elements have the same height. The left div should have 'auto' height while the right one must match it. Moreover, the right div contains 14 nested divs that need to be scr ...

Karma and RequireJS fetching files beyond the base URL

My goal is to set up automatic testing using karma with the following file structure: /assests /css /font /img /js /collection /lib /model /plugin /spec /view test-main.js main.js /templates index.html karma.conf.js In my ...

extract the text content from an object

I am trying to add an object to the shopping cart. The item contains a key/value pair as shown in the following image: https://i.stack.imgur.com/5inwR.png Instead of adding the title with its innerText using p and style, I would like to find another ...