Exploring Array Values within Array of Objects for Specific Value

Here is an array of emojis for you to consider:

allEmojis = {
    "Smileys-People": [
        {
            "index": 1,
            "display": true,
            "name": "grinning face",
            "shortName": ":grinning:",
            "alt": "😀",
            "image": "_81",
            "position": "0px -80px",
            "keywords": [
                "face",
                "nice",
                "smile",
                "laugh",
                "happy",
                "smiling",
                "grin",
                "teeth",
                "cheerful",
                "cheery", 
                "grinning face"
            ]
        },
        {
            "index": 2,
            "display": true,
            "name": "smiling face with open mouth",
            "shortName": ":smiley:",
            "alt": "😃",
            "image": "_81",
            "position": "-60px -80px",
            "keywords": [
                "face",
                "open mouth",
                "awesome",
                "yay",
                "smile",
                "happy",
                "smiling",
                "grin",
                "teeth",
                "smiling face with open mouth"
            ]
        }
    ],
    "Animals-Nature": [
        {
            "index": 3,
            "display": true,
            "name": "grinning face",
            "shortName": ":dog:",
            "alt": "🐶",
            "image": "_82",
            "position": "-60px -20px",
            "keywords": [
                "animal",
                "face",
                "pet",
                "adorbs",
                "dog",
                "puppies",
                "puppy",
                "dog face"
            ]
        },
        {
            "index": 4,
            "display": true,
            "name": "smiling face with open mouth",
            "shortName": ":cat:",
            "alt": "🐱",
            "image": "_82",
            "position": "-60px -80px",
            "keywords": [
                "animal",
                "face",
                "cat",
                "kitten",
                "kitty",
                "pet",
                "cat face"
            ]
        }
    ]
}

I have implemented a javascript code to search within the array and set each display based on the keyword input. However, there are certain discrepancies in the behavior of the function depending on the keyword used.

emojiTitles = Object.keys(allEmojis).join(",").split(',')

const emojiSeacrh = (e) => {
    let value = e.target.value.toUpperCase()
    
    for (let emojiTitle of emojiTitles) {
        for (let emoji of allEmojis[emojiTitle]) {
            for (let keyword of emoji.keywords) {
                if (keyword.toUpperCase().startsWith(value)) {
                    emoji.display = true
                }
                else {
                    emoji.display = false
                }
            }
        }
    }

    allEmojis = allEmojis
}

While I acknowledge that my emojiSearch function may not be optimal, I have struggled to find a better solution that fits my specific requirements after extensive research.

Answer №1

Your code is currently resetting the display at each iteration in the loop, resulting in the final value being only the last match in the array.

for (let keyword of emoji.keywords) {
  if (keyword.toUpperCase().startsWith(value)) {
    emoji.display = true
  } else {
    emoji.display = false
  }
}

A more efficient way to achieve the same outcome would be to simplify the logic using the following:

emoji.display = emoji.keywords.some(keyword => keyword.toUpperCase().startsWith(value));

By utilizing Array.some, you get a direct result based on whether any element meets the condition rather than individually setting the display property for each iteration.

Answer №2

Give this method a shot! 😎

const allEmojis = {"Smileys-People":[{"index":1,"display":true,"name":"grinning face","shortName":":grinning:","alt":"😀","image":"_81","position":"0px -80px","keywords":["face","nice","smile","laugh","happy","smiling","grin","teeth","cheerful","cheery","grinning face"]},{"index":2,"display":true,"name":"smiling face with open mouth","shortName":":smiley:","alt":"😃","image":"_81","position":"-60px -80px","keywords":["face","open mouth","awesome","yay","smile","happy","smiling","grin","teeth","smiling face with open mouth"]}],"Animals-Nature":[{"index":3,"display":true,"name":"grinning face","shortName":":dog:","alt":"🐶","image":"_82","position":"-60px -20px","keywords":["animal","face","pet","adorbs","dog","puppies","puppy","dog face"]},{"index":4,"display":true,"name":"smiling face with open mouth","shortName":":cat:","alt":"🐱","image":"_82","position":"-60px -80px","keywords":["animal","face","cat","kitten","kitty","pet","cat face"]}]};

const keword = 'SMILE';

Object.keys(allEmojis)
  .forEach(key => allEmojis[key] = allEmojis[key].map(obj => ({
    ...obj,
    display: obj.keywords.some(tag => tag.toUpperCase().startsWith(keword))
  })));
  
console.log(allEmojis);
.as-console-wrapper{min-height: 100%!important; top: 0}

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 Sequelize failing to update a row within a database table

This is my first experience using sequelize. Within my database, I have a table named feed containing columns such as ID, caption, and url. In my controller, there is a straightforward function aimed at updating a row within this table: router.patch(' ...

The art of spacing words in a div using spans

Having difficulty with word spacing within a div using spans. Take a look at the following HTML code: <div class="footer-links"> <span><a href="#">Suggestions</a></span> <span>&l ...

Delete an element from an array after a specified timeout period

I'm currently working on a Vue component that is responsible for displaying notifications which should automatically disappear after a set time. My Alert component triggers an 'expired' event and then I handle this event in the parent compon ...

Master the art of adjusting chart width on angular-chart with the help of chart.js

I am currently using angular-chart along with Angular and chart.js to create multiple charts on a single page. However, I am facing an issue where each chart is taking up the entire width of the screen. I have tried various methods to limit the width based ...

Display a complex JSON string in an ng-grid

My web service is designed to generate a JSON string using the following code: JavaScriptSerializer j = new JavaScriptSerializer(); return "[" + string.Join(",", v.getProbingJobs().Select(a => j.Serialize(a)).ToArray()) + "]"; (The getProbingJobs func ...

Guide to utilizing Promise.all within a handler function in React.js

I am currently working on integrating two API calls based on user input; api.js import axios from 'axios'; export const getWeather = input => { }; export const getForecast = input => { }; In my React component: import React, { Compone ...

Repeating data multiple times in ng-repeat directive

Website Development <div ng-app="templeApp" ng-controller="templeList"> <div ng-repeat="temple in temples track by $index" > <h2>{{temple.strTempleName}}</h2> <h4>{{tem ...

The loading of content will happen only after the fadeOut effect

I'm attempting to incorporate content loading between fadeOut and fadeIn. When I execute the code below, the content loads before the fadeOut is complete: $("#contentArea").fadeOut(1000); $("#contentArea").promise().done(); $("#contentArea").load(c ...

Prolong the duration before the submenu closes on a div-based css menu

I have created a unique horizontal menu using DIVs without the use of ul and li lists. Currently, I am searching for a way to delay the collapse of the submenus when the mouse moves out. I don't mind if the solution involves JavaScript, jQuery, or CSS ...

I am facing a challenge in retrieving the chosen item from a drop-down menu on my subsequent page using AngularJS

Here is the code snippet from my app.js file: var countryApp = angular.module('countryApp', ['ngRoute']); countryApp.controller('testController', ['$scope', '$http', '$location', function ($scope ...

`problem encountered when attempting to sanitize HTML through the npm package known as "sanitize-html"`

After researching the documentation, I attempted to use this code snippet: const dirty = '<div>Content</div>'; const clean = sanitizeHtml(dirty); The desired result of 'clean' should be "Content", however it seems that &apo ...

"Sparkling div animation with the use of jQuery's .hover() function

<script> $(document).ready(function () { $("#logo_").hide(); $("#logo_learn").hide(); }) function sl() { $("#logo_learn").slideToggle(500); $("#logo_").fadeIn(); } function hl() { $("#logo_learn").slideToggle(500); $("#logo_ ...

Sorting rows in ag-grid based on custom data displayed by cellRenderer

My goal is to enable column sorting on cell data that includes custom HTML elements. I understand that I might need to create a custom function to override the default sorting behavior and refer it to the raw values instead of the rendered HTML output. De ...

Express 4 app.use not functioning properly

My backend setup is fairly straightforward with a few routes. I prefer to keep the route logic separate from the server.js file, but for some reason, when I make a POST request to the route, it returns a 404 error. In the server.js file: // Import necess ...

Is there a way to update the styling of specific sections of an input field as the user enters text in React?

Just like in most markdown editors, I am looking to enable the ability to modify parts of an input field as the user enters text. For instance: When the user types "_above_", as soon as the second underscore is typed, the text should be styled accordingly ...

Use Meteor to retrieve the value from the initial collection in order to locate the value in the second collection

Currently, I have two sets of data: Users, containing userId, firstname, and surname. Answers, containing answerId, questionId, and user. In the 'Answers' collection, the 'user' field corresponds to the userId of the user who provide ...

Using SAS to create a 2D array for tallying the number of null values in string variables within

In my dataset, I have 10 observations with 6 character variables representing days and cities. Each variable contains either the name of the day or the value 'NA' if the day is missing. Similarly, for city variables, they either have city names o ...

"Utilizing JSON data to implement custom time formatting on the y-axis with AmCharts

Looking to convert minutes to hh:mm:ss format in my JavaScript code var allDataTime = [{ date: new Date(2012, 0, 1), "col": "LONG CALL WAITING", "duration1": '720', "duration2": '57', "duration3": ...

"Enhance Your Browse experience: Chrome Extension that automatically appends content to pages

I'm currently developing a Chrome extension that detects when a URL on a specific domain changes, and if the URL matches a certain pattern, it will add new HTML content to the webpage. Here is an excerpt from my manifest.json file: { "name": "Ap ...

How a JavaScript function handles the scope of a for loop index

Here's some Javascript code I'm working with: func1() { for(i = 2; i < 5; i ++) { console.log(i); func2(i); } } func2(x) { for(i = 100; i < 200; i ++) { do something } } I've noticed that when runni ...