javascript - 如果匹配输入则返回 json 数组

标签 javascript json

需要帮助: 我有 JSON 格式的数组。我似乎无法理解的是当该数组与用户输入匹配时如何处理该数组的所有内容。我可以显示整个数组,并且可以检查输入是否在数组中。

代码:

//user input 
var product  = document.getElementById('product').value;
var price    = document.getElementById('price').value;
var quantity = document.getElementById('quantity').value; 

//Products
var viewInventory = [{
    id : 'a',
    name  : 'iphone',
    model : 10,
    price : 900,
    quantity : 25
}, {    
    id: 'b',
    name  : 'pixel',
    model : 1,
    price : 800,
    quantity : 40
},{
    id: 'c',
    name  : 'pants',
    model : 8,
    price : 700,
    quantity : 80
},{
    id: 'd',
    name  : 'essential',
    model : 10,
    price : 900,
    quantity : 25
}];//end of viewInventory

console.log(viewInventory);//just testing to see it JSON obj works




function hello(){
var item;


for (var i = 0; item = viewInventory[i].name; i++){
    console.log(item);
    // console.log(viewInventory[i].name)


    if (product === item){
        console.log(viewInventory[i]);

        console.log(item + "This is input");
        // document.write(myTable);
    }

}

问题:

下面是我书中的问题(我正在自学)。 将文件中的数据提取到复杂的数据结构中使解析变得更加简单。许多编程语言都支持 JSON 格式,这是一种流行的数据表示方式。

创建一个程序,以产品名称作为输入并检索该产品的当前价格和数量。产品数据位于 JSON 格式的数据文件中,如下所示:

{
_"products" : [
_{"name": "Widget", "price" : 25.00, "quantity": 5 },
__{"name": "Thing", "price": 15.00, "quantity": 5},
__{"name": "Doodad", "price": 5.00, "quantity": 10}
__]
}

如果找到产品,请打印出产品名称、价格和数量。如果没有产品与搜索匹配,请说明未找到产品并重新开始。

示例输出 产品名称是什么? iPad 抱歉,我们的库存中没有找到该产品 产品名称是什么?小工具 名称: 小工具 价格:25.00 美元 现有数量:5个

限制 该文件为 JSON 格式。使用 JSON 解析器从文件中提取值。 如果没有找到记录,则再次提示。 挑战 确保产品搜索不区分大小写。 当未找到产品时,询问是否应添加该产品。如果是,询问价格和数量,并将其保存在 JSON 文件中。确保新添加的产品可立即用于搜索,而无需重新启动程序。

最佳答案

您可以使用Array.prototype.filter函数:

var product  = document.getElementById('product').value;
var price    = document.getElementById('price').value;
var quantity = document.getElementById('quantity').value; 

var matchingProducts = viewInventory.filter((v)=>v.name.indexOf(product)>-1);
if(!matchingProducts.length) alert('Sorry, that product was not found in our inventory');
else {
  alert(
    matchingProducts.reduce(
      (c,i)=>c+i.name+' found with price='+i.price+' and the quantity='+i.quantity+'\n',
      ''
    )
  );
}

关于javascript - 如果匹配输入则返回 json 数组,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/46416177/

相关文章:

javascript - 从给定 URL 获取数据时正确映射到接口(interface)

java - 使用wiremock进行Rest API模拟: java

python - Flask Alchemy with Marshmallow 返回空 JSON

javascript - 如何在循环并进行异步 promise 调用后获取重新格式化的 json 对象

javascript - IE 在不支持的代码后不解析任何 JS?

javascript - 通过映射为对象的属性赋值

json - 数据逐行而不是成批插入

javascript - 在 Node.js 中解析 Reddits JSON Javascript 解析器不喜欢注释

javascript - 添加元素后触发 JavaScript 代码

javascript - 如何仅在执行第一个方法后才执行第二个方法