Finding the attribute value within a nested array of objects retrieved from an API response

Imagine a scenario where I possess an array of unclassified objects, each of which contains an array of labeled objects:

[{id: 123, name: 'Foo', code: 'ABC123', enabled: true},{id: 124, name: 'Bar', code: '123ABC', enabled: true}]

This information has been transformed into an Array of objects as a result of an API call response, leaving all the named objects undefined. Consequently, attempting to access the name property of any object using a code snippet like this:

for (let i = 0; i < resp.length; i++){
    if(resp[i].name = key){do something}
}

(as discussed in the query: Find a value in an array of objects in Javascript) would fail since name remains undefined for the objects within resp.

Is there a method to still access that specific attribute of the object?

Answer №1

I suggest making a slight alteration to your code. The primary issue lies in the fact that you are using the assignment operator (=) instead of the comparison operator (==) in your if statement.

Furthermore, ensure to assign a key and a corresponding word to the value of that key: resp[i][key] == match

const apiResponseArr = [{id: 123, name: 'Foo', code: 'ABC123', enabled: true},{id: 124, name: 'Bar', code: '123ABC', enabled: true}];


function find(resp, match, key) {
  key = key || 'name';
  
  for (let i = 0; i < resp.length; i++){
    if(resp[i][key] == match) { return resp[i]; }
  }

  return 'not found';
}

console.log( find(apiResponseArr, 'Bar') ); // [object]
console.log( find(apiResponseArr, 'Zzz') ); // 'not found'

console.log( find(apiResponseArr, 'ABC123', 'code') ); // [object]

The linked thread provides a shortcut for writing it in a more concise manner:

const apiResponseArr = [{id: 123, name: 'Foo', code: 'ABC123', enabled: true},{id: 124, name: 'Bar', code: '123ABC', enabled: true}];


function find(resp, match, key = 'name') {
  return resp.find(x => x[key] === match);
}

console.log( find(apiResponseArr, 'Bar') ); // [object]
console.log( find(apiResponseArr, 'Zzz') ); // undefined

console.log( find(apiResponseArr, 'ABC123', 'code') ); // [object]

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

Exploring the Differences Between Javascript Ajax Response and String Comparisons

I'm having trouble comparing the result of an ajax call with a string. The ajax call is returning the correct result, but I'm struggling to get the if statement to properly compare it with my string. Any suggestions on how to approach this? ...

"Can you explain the process by which React grabs the props using the code `const props = this.props

I recently came across an interesting article authored by Dan. The example provided in the article caught my attention: class ProfilePage extends React.Component { showMessage = (user) => { alert('Followed ' + user); }; handleClick ...

Tips for selecting a checkbox with Puppeteer

I've implemented the code in this way: await page.$eval('input[name=name_check]', check => { check.checked = true; }); This code is intended for multiple checkboxes. However, I need it to work for a single checkbox only. Is there a way ...

Struggling to update the previousCode state with the useState hook in React

I'm having trouble understanding why the state isn't changing when using setPreviousCode in React and JavaScript. I'm trying to store the previously scanned text in the variable previousCode. import React, { useEffect, useState } from " ...

What is the best way to integrate Bootstrap 5 with Next.js?

After adding Bootstrap to my project with npm install bootstrap, I included the style in /pages/_app.js like this: import 'bootstrap/dist/css/bootstrap.css'; export default function App({ Component, pageProps }) { return <Component {...pag ...

Using ElectronJS requires the usage of the import keyword to load ES Modules

I've recently delved into Electron development by exploring the Electron Docs. I opted for ES6 syntax with import/export, while the documentation showcased the use of require. To align with ES Module standards, I updated my package.json file with typ ...

Invoke a JavaScript function from a dynamically inserted nested function

My primary application loads JavaScript files based on the page being visited: var MainApp = (function() { function loadPage(folder, template) { $.getScript('scripts/' + template + '.js') .done(function() { ...

The error message "Blazor WebAssembly JSRuntime.InvokeVoidAsync - blazor.webassembly.js:1 Uncaught (in promise) TypeError: Converting circular structure to JSON" indicates that

I have implemented the drawio-integration project in my Blazor WebAssembly application. https://github.com/jgraph/drawio-integration This is how the simple helloworld sample appears: <img onclick='DiagramEditor.editElement(this);' src=" ...

Exploration of features through leaflet interaction

Attempting to plot bus routes on a map using leaflet with geojson for coordinates. Facing issues with making the bus line bold when clicked, and reverting the style of previously clicked features back to default. Current Progress function $onEachFeature( ...

Waiting for Promise Js to be fulfilled

I've been exploring the use of Bluebird for handling promises in Node.Js. I have encountered a situation where I need a function to return only when a promise is fulfilled. The desired behavior can be illustrated by the following code snippet: functi ...

The type does not have a property named 'defaultProps'

I have a Typescript React class component structured like this: import React, { Component } from 'react'; interface Props { bar?: boolean; } const defaultProps: Partial<Props> = { bar: false, }; class Foo extends Component<Props& ...

Obtaining the IP address of the client's request

In an effort to prevent others from wasting time in the future, I am sharing this post even though it's not really a question anymore. Objective: Obtain the client IP address and set specific values based on certain octets in the IP address. While w ...

Is there a way to automatically scroll to the last dynamically added div?

Within the chat.html file, I have included a div tag and implemented a script that dynamically adds rows to the div when a button is clicked. In another file named list.html, I have inserted an iframe tag with the src attribute pointing to chat.html. Howev ...

Discovering the significance of a function's scope

I'm a bit confused about how the answer is coming out to be 15 in this scenario. I do understand that the function scope of doSomething involves calling doSomethingElse, but my calculation isn't leading me to the same result as 15. function doSo ...

Having trouble loading my script in the frontend plugin?

After much testing, I have discovered that when I place this code before the get_header() function, the script is successfully loaded. However, when I move it after the get_header() function, it no longer works as intended. It's important to note that ...

Is it time to advance to the next input field when reaching the maxLength?

In my Vue form, I have designed a combined input field for entering a phone number for styling purposes. The issue I am facing is that the user needs to press the tab key to move to the next input field of the phone number. Is there a way to automaticall ...

Particles.js fails to persist as I scroll down the HTML page

After creating a website page, I incorporated Particles.js for the background. However, when I scroll down, the particles seem to be confined to the initial corner of the screen and do not continue downward. Here are my current particle settings: #particl ...

The dynamic route parameter does not currently have compatibility with languages that utilize Unicode characters apart from the English

NextJS 13 (beta) Official Documentation provides information on dynamic route parameters in this link. Clarification: app/shop/[slug]/page.js To retrieve the slug, use params.slug. Example: app/shop/this-is-shop/page.js In this case, params.slug will o ...

Here's a revised version: "How to link a lambda layer with a function in a serverless.ts file using the

When working with the serverless framework using the typescript template, a serverless.ts file is generated. I am currently integrating lambda layers with existing functions and encountering a typescript error. The error message reads: "Type '{ Ref: ...

What could be causing issues with my jQuery POST call?

I am attempting to establish authentication with a remote service using jQuery. Initially, I confirmed that I can accomplish this outside of the browser: curl -X POST -H "Content-Type: application/json" -H "Accept: appliction/json" -d '{"username":" ...