Sorry about the tongue twister title. I have this array:
const languages = [
{
title: '1970s',
languages: [
{
name: 'C',
year: 1972
}
]
},
{
title: '1980s',
languages: [
{
name: 'C++',
year: 1983
},
{
name: 'Perl',
year: 1987
}
]
},
{
title: '1990s',
languages: [
{
name: 'Haskell',
year: 1990
},
{
name: 'Python',
year: 1991
},
{
name: 'Java',
year: 1995
},
{
name: 'Javascript',
year: 1995
},
{
name: 'PHP',
year: 1995
},
{
name: 'Ruby',
year: 1995
}
]
},
{
title: '2000s',
languages: [
{
name: 'C#',
year: 2000
},
{
name: 'Scala',
year: 2003
},
{
name: 'Clojure',
year: 2007
},
{
name: 'Go',
year: 2009
}
]
},
{
title: '2010s',
languages: [
{
name: 'Elm',
year: 2012
}
]
}
];
When the user changes the value of a text input, I want to check if the new value (which I’m saving as var newValue) matches one of the name properties in the above, but the nested nature of the array is causing me headaches. Here’s what I’ve tried:
var result = -1;
function hasName(prop, value, languages) {
languages.forEach(function(obj, index) {
prop.forEach(function(obj, index) {
if (prop in obj && obj[prop] === value) {
result = index;
return false;
}
});
});
return result;
}
if (result != -1) {
alert('HALLO!');
}
prop.forEach is throwing an error. The if statement might do as well, although I can’t test that until I figure out what I should be doing instead of prop.forEach. Would really appreciate a poke in the right direction.
Thanks