Tips for making dynamic keys and values in JavaScript arrays

JSON Input

Data 0: {"eid":12,"gender":"1","age":1,"pass":["2","1"]}
Data 1: {"eid": 11,"gender":"0","age":1,"pass":["1","3"]}
Data 2: {"eid":20,"gender":"1","age":1,"pass":["2","3"]}

How can we create a new array to store IDs based on the pass numbers?

For example, in a loop display:

Pass ID => 2 .... EID => 12, 20

2 => ["12","20"]
1 => [12, 11]
3 => [11,20]

Answer №1

Utilize the filter and some methods to inspect the contents of the pass array and then retrieve the corresponding eid values:

function grabber(data, pass) {
    return data.filter(function (el) {
        return el.pass.some(function (num) {
            return +num === pass;
        })
    }).map(function (el) {
        return el.eid;
    });
}

grabber(data, 1); // [12, 11]
grabber(data, 2); // [12, 20]
grabber(data, 3); // [11, 20]

DEMO

UPDATE

Realized on the way home from work you don't actually need some. Additionally, addressing your comment, here's how you could search for both pass and gender:

function grabber(data, options) {
    return data.filter(function (el) {
        return el.pass.indexOf(options.pass) > -1 && el.gender === options.gender;
    }).map(function (el) {
        return el.eid;
    });
}

grabber(data, { gender: '0', pass: '1' }); // [11]

DEMO

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

Ensuring that hover remains active despite mousedown in JavaScript, CSS, and HTML

It appears that in browser-javascript hover events are deactivated when the mouse button is pressed down, as demonstrated by the following example: (Please run the code snippet to witness what I am referring to.) * { user-select: none; } #click, #drag, ...

Ionic fails to change icon color when loading existing data from server

Apologies for the vague subject, finding it difficult to accurately describe this issue. I have implemented a rating system for specific content. The rating page is displayed in a modal. Initially, when the user rates the content for the first time, every ...

When an iteration occurs within a for loop and a value changes, remember to incorporate a line break or equivalent element using jQuery

I am currently working on implementing a hierarchy system for users stored in a database table. At the moment, only top-level users with a hierarchy of 1 are displayed. When clicked, I use AJAX to retrieve and display all related users below them. These ...

What is the reason behind declaring an array of complex numbers row-wise in fftw?

The Manual for the Fastest Fourier Transform in the West, also known as FFTW, mentions on Page 4 that: The data is represented as an array of type fftw_complex, which is essentially a default double[2] array holding the real (in[i][0]) and imaginary (in ...

Looking to implement pyperclip functionality on Heroku platform

Is it feasible to utilize pyperclip on Heroku with a Selenium application in order to copy something to the clipboard? Since the platform utilizes a 'headless' browser and lacks a GUI, accessing the clipboard is challenging. Is there any way for ...

Send a complex Json object in a POST request

Hey guys, I'm new to the world of web development and I've encountered a challenging issue. I have a complex object with numerous fields filled by a JavaScript function that needs to be passed to a C# HttpPost Call. I attempted to use JSON.Strin ...

Determine the Normalized Mouse Motion Direction Across a Collection Using Three.js

JS Fiddle: http://jsfiddle.net/Nfw9M/1/ I am currently delving into the world of matrix operations and need assistance with a particular problem related to mouse movement on a 3D object. Inside my THREE.Object3D, there are three cube meshes that can be ro ...

The div element fails to display even after invoking a JavaScript function to make it visible

As a newcomer to JavaScript & jQuery, please bear with me as I ask a very basic question: I have created the following div that I want to display when a specific JavaScript function is called: <div id='faix' class="bg4 w460 h430 tac poa ...

The getSession provided by the getSession function is accessible within getServerSideProps but appears as undefined within the component

Whenever I try to log the session variable inside the Dashboard component, it comes back as undefined. However, when I log it inside the getServerSideProps function, it returns the correct details. Am I missing something here? Objective: My goal is to fet ...

The method of altering div content upon clicking a checkbox using a function is ineffective

When adding more else if() statements, the functionality of my custom order form stops working properly. I am in the process of creating a personalized order form for my advertising agency. The form allows users to select items from checkboxes, and the su ...

Creating a Dropdown list using Javascript

I am currently working on implementing inline CRUD operations in MVC 5. When a user clicks a specific button to add new records, it should create a dynamic table row. Below is the JavaScript code I am using: function tblnewrow() { var newrow = ' ...

Having trouble running the THREE.js geometry, text, and shapes example on my personal computer

Currently, I am in the process of learning WebGL and I am looking to incorporate three.js into my work. If you visit this site, you will find a variety of examples that showcase the capabilities of three.js. One specific example titled geometry/ text/sha ...

Utilize React Hook Form to easily reset the value of an MUI Select component

I created a dropdown menu where users can select from "Item 1", "Item 2", and "Item 3". Additionally, there is a "Reset" button that allows users to clear their selection and make a new one. Below is the code I used: import React from ...

What sets apart "config" from "defaults" in Sencha Touch?

As a newcomer to Sencha Touch, I have one simple question that's been on my mind... Can someone explain the distinction between "config" and "defaults" in Sencha Touch? ...

Commitment to provide the outcome of the second promise in case the first one encounters

I am trying to handle the scenario where I need to return the value of a second promise if the first one (value in cache) fails. Below is my code snippet, but I'm encountering an issue where 'resolve' is not defined. exports.getConfig = fu ...

Reorder elements within a 2D array by shuffling the strings

I'm currently working on shuffling the string elements in a 2d array, and I'm facing a dilemma regarding whether to shuffle just the columns or all rows. Here's my progress so far: int main(int argc, char const *argv[]){ char words[4][20] ...

What alternative can I use in PHP instead of array_unique?

I'm encountering an issue with duplicate data in my array that is being stored in the database. Despite using array_unique to filter out duplicates, it's not yielding the desired results. Can anyone suggest an alternative method to ensure unique ...

Tips on how to toggle/close a dropdown menu that is displayed on a different page using Vue

Below is a screenshot of my cart dropdown: https://i.sstatic.net/IdOZK.png The issue I am facing is that the cart stays open even when I navigate to another page. I need it to close when I move to a different page. Below is my component code: <template ...

Retrieving data from Ajax and passing it to PHP

I am currently facing an issue with my Ajax code. When I try to access a textfield variable in PHP after alerting the value successfully, I receive an error stating Undefined index. Javascript Code <SCRIPT> function sendData(UserID) { var name = en ...

Refresh the source dropdown when the x-editable is shown

I need to update the source data for x-editable just before it is displayed in order to ensure that my dropdown menu always displays the most recent entries, even if the source has changed. For more information, you can visit: http://jsfiddle.net/XN7np/3/ ...