If I search for "story" or "ave" or "cell",I should get the first,second and third element respectively for the search.
[
{
"Name": "Mary",
"Subject": "History",
"Marks": "Eighty-nine",
"Grade": "A",
"Remarks": "Good"
},
{
"Name": "Alex",
"Subject": "Science",
"Marks": "Seventy-nine",
"Grade": "B",
"Remarks": "Average"
},
{
"Name": "Taylor",
"Subject": "Mathematics",
"Marks": "Ninety-two",
"Grade": "A+",
"Remarks": "Excellent"
}
]
Any idea on how to do this?
yes. This is basic Javascript.
function searchValues(needle) { var found = []; var re = new RegExp(needle, 'i'); dataset.forEach(function(item, ix) { Object.keys(item).forEach(function(key) { if (typeof item[key] !== 'string') return; if (item[key].match(re)) { if (found.indexOf(ix) === -1) { found.push(ix); } } }); }); return {searched: needle, indexes:found}; } var dataset = [ { "Name": "Mary", "Subject": "History", "Marks": "Eighty-nine", "Grade": "A", "Remarks": "Good" }, { "Name": "Alex", "Subject": "Science", "Marks": "Seventy-nine", "Grade": "B", "Remarks": "Average" }, { "Name": "Taylor", "Subject": "Mathematics", "Marks": "Ninety-two", "Grade": "A+", "Remarks": "Excellent" } ]; var tests = [ "story", "ave", "cell"]; var found = tests.map(searchValues); console.log(JSON.stringify(found, null, 2) + '\n');
If I search for "story" I should get:
[{"Name":"Mary","Subject":"History","Marks":"Eighty-nine","Grade":"A","Remarks":"Good"}]
Will filter work here?
Something of this sort:
if (item[key].match(re))
{ found.push(dataset.filter(re)); }
If I search for "story", I should get:
[
{
"Name":"Mary",
"Subject":"History",
"Marks":"Eighty-nine",
"Grade":"A",
"Remarks":"Good"
}
]
Will filter work here?
Something like this:
var found = dataset.filter(searchValues);
No, try this
var found = searchValues(“story”);
{
"searched": "story",
"indexes": [ 0 ]
}
I am getting this.
I want this for "story":
[
{
"Name":"Mary",
"Subject":"History",
"Marks":"Eighty-nine",
"Grade":"A",
"Remarks":"Good"
}
]
yes - the "indexes" property is telling you which index within the dataset is a match.
var found = searchValues(“story”); // found.indexes is an array var selectedItems = found.indexes.map(function(index) { return dataset[index]; }); console.log(JSON.stringify(selectedItems, null, 2));
Any idea on this?