-1

Say I have the following array of unnamed objects each of which is an array of named objects:

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

This data has been converted into an Array of objects from a API call response, so none of the named objects are defined. For instance I cant check the name of any object using something like:

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

(i.e the solution for the following question: Find a value in an array of objects in Javascript) because name is undefined for the objects in resp.

Is there a way for me to access that attribute on that object?

Nick Ward
  • 13
  • 4

1 Answers1

0

I would just use what your code, but slightly changed. The main error is that you're assigning a variable in your if statement (=) instead of comparing (==).

You also need to add a key and a matching 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]

In your linked thread, you got a suggestion of writing it in an even shorter way:

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]
Rickard Elimää
  • 7,107
  • 3
  • 14
  • 30