问题
Here is a part of my object
const category = {
fr: {
list: [
{id: 1, label: 'coucou'},
{id: 2, label: 'moi'},
{id: 3, label: 'ici'},
{id: 4, label: 'maintenant'},
{id: 5, label: 'demain'},
]}}
const lang = fr;
const anyId = 3;
I don't know why when doing the following:
const result = category[lang].list.find(item => item.id === anyId) console.log(result)
Throws the following:
// undefined category[lang].list.find(item => item.id === anyId) is not a function, or just undefined
same result for .map or .filter
console.log(category)returns no errorconsole.log(category[lang])returns no errorconsole.log(category[lang].list)returns no error
but anything else will return an error. It drives me crazy, any help will be highly appreciated.
回答1:
Use const lang = "fr" instead of const lang = fr, because fr is an undefined variable but "fr" is a string. So you'll get category["fr"] instead of category[fr].
const category = {
fr: {
list: [
{id: 1, label: 'coucou'},
{id: 2, label: 'moi'},
{id: 3, label: 'ici'},
{id: 4, label: 'maintenant'},
{id: 5, label: 'demain'},
]}}
const lang = "fr";
const anyId = 3;
const result = category[lang].list.find(item => item.id === anyId)
console.log(result)
回答2:
You want category.fr not just fr, as the variable fr does not exist.
Now that lang contains your fr object, you can simply do a .find() on lang.list as below:
const category = {
fr: {
list: [
{id: 1, label: 'coucou'},
{id: 2, label: 'moi'},
{id: 3, label: 'ici'},
{id: 4, label: 'maintenant'},
{id: 5, label: 'demain'},
]}}
// Fill param from a variable, or anything, as long as it's a string:
const param = 'fr';
// Use brackets here, as you want `category.fr` and not `category.param`:
const lang = category[param];
//Or you can simply use:
//const lang = category.fr; //If this is not a parameter, or user input
const anyId = 3;
console.log(lang);
console.log(lang.list.find(item => item.id === anyId));
回答3:
It works on mdn sandbox
const category = {
fr: {
list: [
{id: 1, label: 'coucou'},
{id: 2, label: 'ici'},
{id: 3, label: 'demain'},
{id: 4, label: 'matin'},
]
}
};
var lang ='fr';
var catID = 3;
console.log(lang);
console.log(catID);
console.log(category);
console.log(category[lang]);
console.log(category[lang].list);
var found = category[lang].list.find(function(element) {
return element.id === catID;
});
console.log(found.label); // demain
just add a return inside the callback function, but it still doesn't work on react-native so the problem remains
来源:https://stackoverflow.com/questions/48951612/method-find-javascript-deep-array-object-rn-react-native