I am reading some JSON into a 2D JS object as follows:
$.getJSON("file.json", function(arr) {
dict = arr;
});
Example when I do console.log(dict[1]); - there are thousands of such rows:
{
"ortho": "a",
"phon": "a",
"lemme": "a",
"cgram": "NOM",
"genre": "m",
"nombre": "",
"freqlemfilms2": "81.36",
"freqlemlivres": "58.65",
"freqfilms2": "81.36",
"_freqlivres": "58.65",
"_infover": "",
"_nbhomogr": "3",
"_nbhomoph": "9",
"_islem": "1",
"_nblettres": "1",
"_nbphons": "1",
"_cvcv": "V",
"_p_cvcv": "V",
"_voisorth": "25",
"_voisphon": "20",
"_puorth": "1",
"_puphon": "1",
"_syll": "a",
"_nbsyll": "1",
"_cv-cv": "V",
"_orthrenv": "a",
"_phonrenv": "a",
"_orthosyll": "a",
"_cgramortho": "NOM,AUX,VER",
"_deflem": "",
"_defobs": "",
"_old20": "1",
"_pld20": "1",
"_morphoder": "a",
"_nbmorph": "1",
"no": "1"
}
I'm then trying to filter this to yield all rows (result) where orth is a particular value.
const asArray = Object.entries(dict);
const result = asArray.filter(word => word.ortho === 'a');
console.log(result);
This yields an empty array although I know there are several results. Please could someone advise what I've missed out? Thanks!
CodePudding user response:
The problem is in your use of Object.entries()
. Object.entries
returns an array of [key, value]
tuples, so your filter callback doesn't make sense as it is. (It is trying to access ortho
on an array...[1, {"ortho": "a", "phon": "a", ... }].ortho
)
Instead, if dict
is an object, you need to filter the dict
values.
const dict = { 1: {"ortho": "a", "phon": "a", }, 2: {"ortho": "a", "phon": "a",},}
const result = Object.values(dict).filter(word => word.ortho === 'a');
I've only guessed that dict
is an object from your inferences, if it is actually an array, then just filter it directly.
const dict = [ {"ortho": "a", "phon": "a", }, {"ortho": "a", "phon": "a",},]
const result = dict.filter((word) => word.ortho === 'a');
Edit (In response to your comment re: filtering by an array)
If you want to filter for multiple values you can declare an array and use Array#includes()
to check if the value is included.
const dict = [ {"ortho": "a", "phon": "a", }, {"ortho": "a", "phon": "a",},];
const filter_array = ['a', 'c'];
const result = dict.filter((word) => filter_array.includes(word.ortho));
Or, if you wanted to also specify the properties to you could declare an array of [key, value]
tuples to check against in your filter call. Here using Array#some()
which will match if any matches are found, but you could replace it with Array#every()
if you wanted only elements that match all conditions.
const dict = [ {"ortho": "a", "phon": "a", }, {"ortho": "a", "phon": "a",},]
const filter_tuples = [['ortho', 'a'],['phon', 'b'],];
const result = dict.filter((word) => filter_tuples.some(([k, v]) => word[k] === v));