Я немного потерялся в упражнении, которое я делал сегодня днем. У меня есть информация в массиве JSON, например:
var json = [
{
"recipe": {
"URL": "www.google.com",
"Title": "theTitle",
"Time": "theTime",
"Ingredients": "... tomato potato orange ...",
"Image": "theImage"
}
},
{
"recipe": {
"URL": "www.google.com",
"Title": "theTitle",
"Time": "theTime",
"Ingredients": "... tomato orange potato and fish...",
"Image": "theImage"
}
},
{
"recipe": {
"URL": "www.google.com",
"Title": "theTitle",
"Time": "theTime",
"Ingredients": "... nothing ...",
"Image": "theImage"
}
},
{
"recipe": {
"URL": "www.google.com",
"Title": "theTitle",
"Time": "theTime",
"Ingredients": "... nothing ...",
"Image": "theImage"
}
}
]
И я пытаюсь получить позицию в JSON, если она совпадает с одной из моих переменных. Вот пример того, что я пытаюсь сделать:
var matches = ["tomato","potato"]
for (var i = 0; i < json.length;i++){
if (json[i].recipe.Ingredients == matches) {
alert("I got something :" + json[i])
}
else {
nothing}
}
Поэтому я попытался с помощью регулярного выражения, но это не сработало. Любая идея, как я должен это делать? Извините, если это может показаться глупым, я все еще новичок в кодировании: D!
Решением может быть:
new RegExp(matches.join('|')).test(json[i].recipe.Ingredients)
где:
matches.join('|') → "томатный картофель"
новый RegExp (matches.join('|')) ->/tomato | potato/(regex)
json [i].recipe.Ingredients → - это содержимое ингредиентов
test - метод выполняет поиск совпадения между регулярным выражением и указанной строкой. Возвращает true или false.
var json = [
{
"recipe": {
"URL": "www.google.com",
"Title": "theTitle",
"Time": "theTime",
"Ingredients": "... tomato potato orange ...",
"Image": "theImage"
}
},
{
"recipe": {
"URL": "www.google.com",
"Title": "theTitle",
"Time": "theTime",
"Ingredients": "... tomato orange potato and fish...",
"Image": "theImage"
}
},
{
"recipe": {
"URL": "www.google.com",
"Title": "theTitle",
"Time": "theTime",
"Ingredients": "... nothing ...",
"Image": "theImage"
}
},
{
"recipe": {
"URL": "www.google.com",
"Title": "theTitle",
"Time": "theTime",
"Ingredients": "... nothing ...",
"Image": "theImage"
}
}
];
var matches = ["tomato", "potato"]
for (var i = 0; i < json.length; i++) {
if (new RegExp(matches.join('|')).test(json[i].recipe.Ingredients)) {
console.log("I got something :" + JSON.stringify(json[i]))
}
else {
console.log('nothing');
}
}
Спасибо вам обоим ! Последний вопрос, мой JSON получит около 60 тыс. Предметов. Как вы думаете, я могу остановиться на этих методах поиска или мне абсолютно необходимо создать API?
Вот мое решение без использования Regex
.
var json = [
{
"recipe": {
"URL": "www.google.com",
"Title": "theTitle",
"Time": "theTime",
"Ingredients": "... tomato potato orange ...",
"Image": "theImage"
}
},
{
"recipe": {
"URL": "www.google.com",
"Title": "theTitle",
"Time": "theTime",
"Ingredients": "... tomato orange potato and fish...",
"Image": "theImage"
}
},
{
"recipe": {
"URL": "www.google.com",
"Title": "theTitle",
"Time": "theTime",
"Ingredients": "... nothing ...",
"Image": "theImage"
}
},
{
"recipe": {
"URL": "www.google.com",
"Title": "theTitle",
"Time": "theTime",
"Ingredients": "... nothing ...",
"Image": "theImage"
}
}
]
var matches = ["tomato","potato"]
for (var i = 0; i < json.length;i++){
matches.forEach(function(word){
if(json[i].recipe.Ingredients.indexOf(word) > -1){
console.log(json[i]);
} else {
console.log("doesn't exist");
}
});
}
RegExp
? Я думаю, что это не подходит.