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?
CodePudding user response:
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]
CodePudding user response:
Never use assignment (=
) inside an if
's condition!
Use either loose (==
) or strict (===
) equality.
In other words, you should replace resp[i].name = key
with either resp[i].name == key
or resp[i].name === key
, depending on the value of key
(which you haven't shown).
The code you have shown:
for (let i = 0; i < resp.length; i ){
if(resp[i].name = key){do something}
}
assigns the value of key
to the name
property of every single object in your array and does not perform do something
, because an assignment returns undefined
.