我是JSON和JS的新手,我希望有人可以帮助我。我正在使用两个单独的JSON文件。配方JSON文件具有 ID 字段和 ingredientNum 字段。在我的第二个JSON文件中,我需要将第一个JSON文件中的 ingredientNum 与第二个JSON文件中名为 itemFullUPC 的相应字段进行匹配。如果字段中存在匹配项,我需要使用与正确itemUPC对应的第二个JSON文件中的itemName替换无序列表中页面上显示的当前componentNum。下面是数据库和我的代码。希望有人可以帮助我!
食谱JSON示例:
[
{
"recipeName":"Test",
"id":"10",
"ingredients":[
{
"ingredientNum":"070796501104",
"ingredientMeasure":"1 bottle",
"ingredientMisc1":"(33.8 fl oz)"
},
{
"ingredientNum":"070796000164",
"ingredientMeasure":"1/2 cup",
"ingredientMisc1":""
}
]
}
]
产品JSON示例:
[
{
"productName":"Tomatoes",
"itemFullUPC":"070796501104"
},
{
"productName":"Cherries",
"itemFullUPC":"070796000164"
}
]
例如,在第二个数据库中。 productName名为" Cherries"在第一个数据库中具有相同的编号,我需要用项目名称替换当前在页面上生成的列表。
预期输出
我需要为整个列表或匹配的任何内容执行此操作。我把我的尝试包括在内,谢谢。
$(document).ready(function() {
'use strict';
$.ajax({
url: 'path to recipeDB',
cache: true,
success: function(data){
data = data.replace(/\\n/g, "\\n")
.replace(/\\'/g, "\\'")
.replace(/\\"/g, '\\"')
.replace(/\\&/g, "\\&")
.replace(/\\r/g, "\\r")
.replace(/\\t/g, "\\t")
.replace(/\\b/g, "\\b")
.replace(/\\f/g, "\\f");
data = data.replace(/[\u0000-\u0019]+/g,"");
var json = JSON.parse(data);
$.ajax({
dataType: "jsonp",
url: 'path to itemDB',
cache: true,
success: function(itemData){
var product_data = itemData;
var productUPC = '';
var productName = '';
$.each(product_data, function(i, item) {
productUPC += item.itemFullUPC;
productName += item.itemName;
});
var ingredients = '';
$.each(json, function(i, item) {
if (item.id == "10") {
ingredients += '<ul>';
for (var i = 0; i < item.ingredients.length; i++) {
ingredients += '<li>' + item.ingredients[i].ingredientMeasure + ' ' + item.ingredients[i].ingredientNum + ' ' + item.ingredients[i].ingredientMisc1 + '</li>';
}
ingredients += '</ul>';
}
});
$('#recipeIngredients').html(ingredients);
}
});
}
});
});
我成功地从第一个数据库开始使用列表,但我不知道如何链接到第二个数据库并将项目从列表中的UPC更改为项目名称。
答案 0 :(得分:1)
您可以使用Array.prototype.map()
和Array.prototype.find()
var recipe = [{
"recipeName": "Test",
"id": "10",
"ingredients": [{
"ingredientNum": "070796501104",
"ingredientMeasure": "1 bottle",
"ingredientMisc1": "(33.8 fl oz)"
}, {
"ingredientNum": "070796000164",
"ingredientMeasure": "1/2 cup",
"ingredientMisc1": ""
}]
}];
var product = [{
"productName": "Tomatoes",
"itemFullUPC": "070796501104"
}, {
"productName": "Cherries",
"itemFullUPC": "070796000164"
}];
recipe.ingredients = recipe[0].ingredients.map(function(o) {
o.ingredientName = product.find(function(p) {
return p.itemFullUPC === o.ingredientNum;
}).productName;
return 0;
});
console.log(recipe);
答案 1 :(得分:0)
使用Array.prototype.forEach()和Array.prototype.some()函数的解决方案:
var recipes = [{"recipeName":"Test","id":"10","ingredients":[{"ingredientNum":"070796501104","ingredientMeasure":"1 bottle","ingredientMisc1":"(33.8 fl oz)"},{"ingredientNum":"070796000164","ingredientMeasure":"1/2 cup","ingredientMisc1":""}]}],
products = [{"productName":"Tomatoes","itemFullUPC":"070796501104"},{"productName":"Cherries","itemFullUPC":"070796000164"}];
recipes[0].ingredients.forEach(function (recipe) {
products.some(function (product) {
var cond = product.itemFullUPC === recipe.ingredientNum;
if (cond) {
recipe.ingredientNum = product.productName;
}
return cond;
});
});
console.log(recipes);
现在,您可以遍历配方成分并填写无序列表
答案 2 :(得分:0)
假设你有一个食谱数组,你可以像这样重新映射数组:
var recipes = [{
"recipeName": "Test",
"id": "10",
"ingredients": [{
"ingredientNum": "070796501104",
"ingredientMeasure": "1 bottle",
"ingredientMisc1": "(33.8 fl oz)"
}, {
"ingredientNum": "070796000164",
"ingredientMeasure": "1/2 cup",
"ingredientMisc1": ""
}]
}]
var ingredients = [{
"productName": "Tomatoes",
"itemFullUPC": "070796501104"
}, {
"productName": "Cherries",
"itemFullUPC": "070796000164"
}]
recipes = recipes.map(function(recipe) {
return $.extend(recipe, {
ingredients: recipe.ingredients.map(function(ingr) {
return $.extend(ingr, {
productName: ingredients.find(function(el) {
return ingr.ingredientNum == el.itemFullUPC;
}).productName || ""
});
})
});
});
console.log(recipes);
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
答案 3 :(得分:0)
我会将产品数组更改为一个对象,这样您就不必在其上循环以查找产品。如果您可以更改服务器以使用键而不是数组返回对象,那将是一个奖励。
var recipe = [{
"recipeName": "Test",
"id": "10",
"ingredients": [{
"ingredientNum": "070796501104",
"ingredientMeasure": "1 bottle",
"ingredientMisc1": "(33.8 fl oz)"
}, {
"ingredientNum": "070796000164",
"ingredientMeasure": "1/2 cup",
"ingredientMisc1": ""
}]
}];
var products = [{
"productName": "Tomatoes",
"itemFullUPC": "070796501104"
}, {
"productName": "Cherries",
"itemFullUPC": "070796000164"
}];
//change products to object for easier lookup
var prodHash = products.reduce(function(o, item) {
o[item.itemFullUPC] = item.productName;
return o;
}, {});
var ingredients = recipe[0].ingredients.map(function(item) {
return "<li>" + item.ingredientMeasure + (item.ingredientMisc1.length ? " " + item.ingredientMisc1 + " " : " ") + prodHash[item.ingredientNum] + "</li>";
}).join("");
document.getElementById("out").innerHTML = ingredients;
<ul id="out"></ul>
答案 4 :(得分:0)
首先是旁注:
$keys = array_keys($myArray); // fetches all the keys
$firstElement = $myArray[$keys[0]]; // Get the first element using first key
所以代码:
//these don't do anything, you're literally replacing these strings with the very same strings
data = data.replace(/\\n/g, "\\n")
.replace(/\\'/g, "\\'")
.replace(/\\"/g, '\\"')
.replace(/\\&/g, "\\&")
.replace(/\\r/g, "\\r")
.replace(/\\t/g, "\\t")
.replace(/\\b/g, "\\b")
.replace(/\\f/g, "\\f");
//and these should usually not be in the JSON-string
data = data.replace(/[\u0000-\u0019]+/g, "");
修改强>
配方数据集实际上是一个格式化为数组的php文件,因此我无法使用json p
我在那里使用了jsonp,因为另一个请求也是jsonp。
$(document).ready(function() {
'use strict';
//first let's make the ajax-calls parallel
$.when(
$.ajax({
dataType: "jsonp",
url: 'path to recipeDB',
cache: true
}),
$.ajax({
dataType: "jsonp",
url: 'path to itemDB',
cache: true
})
).then(function(recipes, products){
//now let's convert the products into a more useful structure
var productsByUPC = products.reduce(function(acc, item){
acc[ item.itemFullUPC ] = item.productName;
return acc;
}, {});
//a sinple utility
//and don't be shy to use long and speaking names
//it's not your task to minify your code, it'the minifiers task
//and due to autocompletition one can not even brag about having to much to type
function formatIngredientAndAddName( ingredient ){
//here it makes no sense to add "ingredient" to each property name
//do you think, that `ingredient.ingredientMeasure`
//has any benefit over `ingredient.measure`
return {
name: productsByUPC[ ingredient.ingredientNum ],
measure: ingredient.ingredientMeasure,
misc: ingredient.ingredientMisc1
}
}
//and clean up the recipes
return recipes.map(function(recipe){
return {
id: recipe.id,
name: recipe.recipeName,
ingredients: recipe.ingredients.map( formatIngredientAndAddName )
}
});
}).then(function(recipes){
//now we have some clean data, containing all we need,
//let's create some markup
function ingredient2Markup(ingredient){
return '<li>'
+ ingredient.measure
+ ' '
+ ingredient.name
+ ' '
+ ingredient.misc1
+ '</li>';
}
function recipe2Markup(recipe){
return '<ul>' +
recipe.ingredients
.map( ingredient2Markup )
.join("")
+'</ul>';
}
$('#recipeIngredients').html(
recipes.map( recipe2Markup ).join("\n")
);
})
});