Is there a way to cycle through each element within a loop and output a corresponding item from another array?

My data structure consists of an array of objects like this:

arrOfObjs =
[{type: "flower", egg: "something"},
{type: "flower", egg: "something2"},
{type: "notFlower", egg: "something3"},
{type: "flower", egg: "something4"}]

Each object in the array has a 'type'. When a user clicks on an item, another object is added to the array with type either "flower" or "notFlower"

I also have a separate array structured like this:

allProperties = 
["flower_style_1",
"flower_style_2",
"flower_style_3",
"flower_style_4",
"flower_style_5",
"flower_style_6",
"flower_style_7",
"flower_style_8"]

The naming convention for each item in allProperties is flower_style_ followed by a number up to 8.

For every item in arrOfObjs with type = "flower", as well as any new items added, I need to return a corresponding property from the allProperties array.

For example, based on the arrOfObjs provided:

  1. For {type: "flower", egg: "something"} => return "flower_style_1".
  2. For {type: "flower", egg: "something2"} => return "flower_style_2".
  3. No return value for {type: "notFlower", egg: "something3"} because it's not of type "flower".
  4. For {type: "flower", egg: "something4"} => return "flower_style_3".
  5. And so on...

Once all items in allProperties have been returned, the cycle starts from flower_style_1 and continues for each new item added to arrOfObjs.

I currently have a foreach loop iterating through arrOfObjs implemented as shown below:

    this.arrOfObjs?.forEach(arrItem => {
        if (arrItem.type === 'flower') {
            this.allProperties.forEach(element => {
                return element;
            }
        }
    });

However, this approach does not function properly, and I am looking for a more efficient way to achieve this without relying on an array containing flower_style_.......

If you have any suggestions on how to accomplish the above scenario, I would greatly appreciate your input.

Answer №1

      collectionOfObjects =
[{type: "flower", egg: "something"},
{type: "flower", egg: "something2"},
{type: "notFlower", egg: "something3"},
{type: "flower", egg: "something4"}]

allCharacteristics = 
["flower_style_1",
"flower_style_2",
"flower_style_3",
"flower_style_4",
"flower_style_5",
"flower_style_6",
"flower_style_7",
"flower_style_8"];


let resultsArray=[]; 
collectionOfObjects?.forEach((object, index) => {
        if (object.type === 'flower') {
            resultsArray.push(allCharacteristics[resultsArray.length]);
        }
    });  
    console.log(resultsArray);

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

Default behavior in Fullcalendar 6 allows for rendering links on both days of the month and weekdays

Is there a way to customize the rendering of days and weekdays in Fullcalendar React? Currently, they are displayed as links by default (<a>{dayContent}</a>), but I'm looking to have them rendered as <div> or <span>. Any sugges ...

I'm unable to utilize the setMarcaCelular setter method on an array

I am having trouble using the setter method setMarcaCelular on an array clientes[i]. I suspect the issue may be with the switch statement, but I'm not sure why. I am still learning Java and tend to get lost easily. Here is the error message I am recei ...

Discover the most helpful keyboard shortcuts for Next.js 13!

If you're working with a standard Next.js 13 app that doesn't have the experimental app directory, setting up keyboard shortcuts can be done like this: import { useCallback, useEffect } from 'react'; export default function App() { c ...

Obtaining a result from a switch statement

Here is a solution to populate the generated drop-down menu: $('dropdown_options').innerHTML = '&nbsp;'; jsonResponse.forEach(function(element){ $('dropdown_options').innerHTML += '<option value='+ elemen ...

Jackson: What is the safest way to share an ObjectMapper? Are there any ways to create an immutable ObjectMapper?

The Mapper instances are completely thread-safe, eliminating the need to create a new mapper for each use. However, it is important to note that the configuration of a mapper can be altered. While ObjectMapper does have a copy function to duplicate config ...

Can pins be added or removed from a location plan (image or vector) using either Javascript or the DevExpress library?

At the factory where I am employed, there are close to 1000 cameras in operation. I have requested to have the locations of these cameras marked on a non-geographical map of the factory. By simply clicking on one of the camera icons, it should be possible ...

Regular Expression to Replace Characters Not Matching

I am struggling with a coding issue that involves manipulating a string. The original string I have is "Hello This is world This". Here is the code snippet I have tried: var patt = 'Hello This is world This' var res = patt.constructor; alert( ...

Preventing page navigation in JavaScript: Why it's so challenging

I am encountering an issue with a link element that I have bound a click event to (specifically, all links of a certain class). Below is an example of the link element in question: <a id="2" class="paginationclick" style="cursor: pointer;" href=""> ...

A step-by-step guide on converting request.body to JSON in Django

Whenever I send a post request to my Django server using Postman or my Android app, the request.body is received in the format user=abc&pwd=123 instead of JSON. How can I parse this format into JSON using Python? ...

Is there a way to verify if an array has been initialized and holds a value simultaneously?

Is there a more concise and elegant way to check if ['pk'] exists in the first item of an array before executing certain tasks? The array may not always have data, leading to bloated code. I'm looking for a streamlined solution in Javascrip ...

Find text within a series of brackets

Dealing with a long JSON string can be tricky, especially when trying to filter out specific data between brackets. If you have multiple nested brackets, your regex pattern may not work as expected. Let's take a look at the JSON string: String j ...

What is the best way to ensure that only one accordion tab remains open at a time, preventing it from closing unless a different tab

How can I ensure that only one accordion tab is open at a time, automatically closing any others that are currently open? Here is my current code for the accordion: $('[data-bs-toggle="collapse"]').on('click', function(e) { if ($( ...

Divide and store parts in an array

Is there a method to split a string at a specific character and include that character in the resulting array? For instance, if we split the string "hello ??? world" at ???, the resulting array would be ["hello ", "???", "world"]. It's worth noting ...

Is it advisable to encapsulate my entire Express server within a TypeScript class?

After working extensively with nodeJs, I have decided to explore developing applications in Typescript. Recently, I came across various blogs (like this one) that recommend wrapping modules and the app's entry point in a class when creating a RESTful ...

Tips for conserving memory while working with large JSON files using GSON Streaming

In my JSON data, I have a few reportRecords for demonstration purposes but in reality, the JSON can be much larger with multiple reportRecords. These records contain various metrics and dimensions related to different pools and environments. { "aggReco ...

Passing props through Link in React can be a tricky process, especially when encountering issues with undefined props like this

My latest project involves creating a recipe research tool in react. The homepage features buttons that allow me to search for recipes and view them based on the data I gather. However, when I try to access the state values using 'console.log(this.pro ...

Instructions on filling the star icon with color upon clicking the button

Currently working on a project using codeIgniter where I have a form for rating products. I am facing an issue where, upon clicking the star button, only the border color changes to yellow while the center of the button remains white. Can someone please g ...

How to use OBJLoader/Three.js to load a specific URL in JavaScript

I am encountering an issue with a JavaScript code snippet from the three.js OBJloader. I should mention that my experience level in JS and PHP is limited as I am just starting out with WordPress websites. My problem lies in utilizing the setPath and load ...

Guide to sending JSON data to a remote API using Coldfusion's CFHTTP

I seem to be struggling with this task, but I have made some progress thanks to the support of fellow Stack Overflow users. I appreciate the help so far. My goal is to send JSON data via a POST request to a remote API. Unfortunately, using jQuery is not a ...

Difficulty encountered while parsing JSON object

I'm encountering an issue with storing JSON data in a class. I am struggling to correctly handle the second JSON line labeled as BadGuy. Its data is not being stored properly. { \"First\":{\"FirstBool\":1, \"aString&bsol ...