Retrieve the property of an object from within an array

I am dealing with an array structure like this:

const arr = [{
    name: 'One',
    id: 1
  },
  {
    name: 'Two',
    id: 2
  }
];

My goal is to extract and return the name of the object if its id matches a certain value.

After experimenting with different approaches, I found that my solution returned the entire object within an array instead of just the name:

const arr = [{
    name: 'One',
    id: 1
  },
  {
    name: 'Two',
    id: 2
  }
];

const getNameFromId = id => {
  return arr.filter(item => {
    if (item.id === id) {
      return item.name;
    }
  })
}

const res = getNameFromId(1)
// This should return `'One'`
console.log(res)

Answer №1

If you're searching for an item, consider using the find method.

const targetId = 2
arr.find(item => item.id === targetId).name

It's important to verify whether the find method returns a value or not.

const getNameFromId = id => {
  const result = arr.find(item => item.id === id)
  if (result) {
    return result.name
  }
}

Answer №2

If you decide to use the filter method, which results in an array being returned, you have the option to extract the name property from the first element. On the other hand, utilizing the find method as suggested in the previous response might be more suitable for your specific requirements.

const arr = [{ name: 'One', id: 1 }, { name: 'Two', id: 2} ];

const getNameFromId = (id) => {
  return arr.filter(item => item.id === id)[0].name;
}

const result = getNameFromId(1)
console.log(result)

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

Tips for concealing a particular button that shares the same class designation

Is there a way to create a function in vanilla JavaScript that can hide a specific button? <button class"btn">button 1 </button> <button class"btn">button 2 </button> <button class"btn">button 3 </button> Specifically, ...

Is Typescript familiar with the import -> require syntax, but unfamiliar with the require -> import syntax?

My code includes a simple file that utilizes the ES6 module loader: 1.ts import {foo} from "./2" foo('hello'); 2.ts function foo (a){console.log(a);}; export {foo} When the tsconfig is configured as follows: "module": "commonjs", We can o ...

Error encountered in MySQL and NodeJS: Unable to add new query after invoking quit with transactions

While working on implementing MySQL for NodeJS and Restify, I encountered a flawless experience with queries. However, when attempting to utilize data updating functionality through transactions, I faced the error message: Error: Cannot enqueue Query after ...

Basic Ajax script fails to function properly

I'm having trouble with the external website that is supposed to output valid JSON data. The code seems too simple for there to be an issue, I've tried using both get and post methods. $(document).ready(function() { $.get("https://www.w3scho ...

When using Javascript, you can expect to receive a modified structure that is different from

I am dealing with an array of objects that have the following structure: const data: [ { id: 21786162, label: "cBTC 2021-06-25 Put $50,000.00", active": true, type: "put", strike_price: 5000000, date_live: "2019-11- ...

Transfer a script from a view to application.js in Rails: Guide and Instructions

After conducting some research, I found a code that worked well for me in the view. However, I am looking to transfer it to application.js so that I can utilize it in various forms. Another issue I encountered is having two scripts performing the same fun ...

The addClass and removeClass functions seem to be malfunctioning

Hey everyone, this is my first time reaching out for help here. I looked through previous questions but couldn't find anything similar to my issue. I'm currently working on a corporate website using bootstrap3 in Brackets. I've been testing ...

Implementing a Vue.js v-bind:style attribute onto a dynamically generated element post-page initialization

Let me start by explaining my current issue and dilemma: I have been tasked with converting an existing JS project into a Vue.js framework. While I could easily solve a particular problem using jQuery, it seems to be posing quite a challenge when it comes ...

Utilizing Angular2 Observables for Time Interval Tracking

I'm working on a function that needs to be triggered every 500ms. My current approach in angular2 involves using intervals and observables. Here's the code snippet I've implemented so far: counter() { return Observable.create(observer =&g ...

Error: Unable to assign a value to the statusCode property because it

During the development of my application backend, I encountered an error while working on the user login route. When testing the route using Postman, I received the following error message: UnhandledPromiseRejectionWarning: TypeError: Cannot set propert ...

Setting the variable to global does not apply styling to the element

Looking for help with styling an element created using document.createElement("img")? let fireball; //global variable fireball = document.createElement("img") //variable on local fireballArray.push(someFunction(fireball, { src: "img.png&qu ...

Learn how to use canvas and JavaScript to draw lines that display x and y coordinates on top of the mouse pointer at the same time

Implement a functionality in which lines are drawn while the mouse button is held down and simultaneously display x & y coordinates on top of the mouse pointer during mouse movement using canvas and JavaScript. The issue arises when attempting to draw lin ...

Knockout.js dropdown pre-selection in nested JavaScript objects is functioning smoothly in KO 2x versions, but there seems to be a compatibility issue with KO 3x versions

This is a sample data that will be loaded from the server in JSON format and constructed into the below object graph. It consists of an array of "Choice" objects, each with properties like id, name, stages, & currentStageId. The "stages" property in th ...

Is there anybody who can assist me with ${}?

Having an issue with using ${'variable'+i} in a loop function. The goal is to call each function from a loop. Explored template literals but couldn't find a solution for this specific problem. Desired format: ${'variable'+i} // (w ...

What is the reason behind appending a timestamp to the URL of a JavaScript resource?

$script.ready('jui',function() { $script('<?php base_path(); ?>js/partnerScripts.js?ts=1315442861','partners'); }); Can anyone explain why there is a fixed ts=timestamp at the end of the partnerScripts.js file name? I ...

What is the process of integrating an ejs view engine with express on Netlify?

Need help configuring the ejs view engine with netlify I attempted to set app.set('view engine', 'ejs'), but didn't see any results. const express = require('express'); const path = require('path'); const serv ...

How can I access the parent elements within a recursive directive?

I'm currently implementing a recursive directive called https://github.com/dotJEM/angular-tree to iterate through a model structure like the one below: $scope.model = [ { label: 'parent1', children: [{ ...

Trigger an event in Vue with specified parameters

I am attempting to emit a function with parameters in the following way. template: ` <div class="searchDropDown"> <div class="dropdown is-active"> <div class="dropdown-trigger"> <button class="button" aria-haspopup=" ...

The addition of the woocommerce_add_to_cart action is causing issues with the website's native add to cart

After creating a node express API that listens for post requests from the woocommerce_add_to_cart webhook, I noticed that the payload it receives is not very useful. body:{ action: 'woocommerce_add_to_cart', arg:'098uoijo098920sa489983jk&ap ...

Ways to prevent recurring variables in Twitter bootstrap dialogues

I need assistance with deleting multiple links using ajax: <a id="id-1">link1</a> <a id="id-2">link2</a> <a id="id-3">link2</a> <a id="id-4">link2</a> ... This is the simplified version of my code: $(docum ...