Return json array if matches input - javascript

Need help:
I have my JSON formatted array. What I can't seem to wrap my head around is how to all the contents of said array when it matches user input. I can display the whole array and i can check if the input is in the array.
Code:
//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);
}
}
Problem:
Below is the problem from my book ( i am self learning).
Pulling data from a file into a complex data structure makes parsing much simpler. Many programming languages support the JSON format, a popular way of representing data.
Create a program that takes a product name as input and retrieves the current price and quantity for that product.The product data is in a data file in the JSON format and looks like this:
{
_"products" : [
_{"name": "Widget", "price" : 25.00, "quantity": 5 },
__{"name": "Thing", "price": 15.00, "quantity": 5},
__{"name": "Doodad", "price": 5.00, "quantity": 10}
__]
}
Print out the product name, price, and quantity if the product is found. If no product matches the search, state, that no product was found and start over.
Example output
What is the product name? iPad
Sorry, that product was not found in our inventory
What is the product name? Widget
Name: Widget
Price: $25.00
Quantity on hand: 5
Constraints
The file is in the JSON format. Use a JSON parser to pull the values out of the file.
If no record is found, prompt again.
Challenges
Ensure that the product search is case-insensitive.
When a product is not found, ask if the product should be added. If yes, ask for the price and the quantity, and save it in the JSON file. Ensure the newly added product is immediately available for searching without restarting the program.

you can use the Array.prototype.filter function:
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',
''
)
);
}

Related

I am trying to sort through my array producing a new array that will give me the resulting array of products over 1500 [duplicate]

This question already has answers here:
Map and filter an array at the same time
(16 answers)
Closed 12 months ago.
Here is the problem:
recieve an array
produce an array with the persons name and number of products id above 1500 and if they are below 1500 (1436 - 1600 ) you cant include them.
customers = [ { name :" stacy "
age : "45"
products ordered id : "1500 - 1600"
}
name : "ashley"
age : "87"
products ordered id : "1455 - 1660"
}
name: " gabrielle"
age : "67"
products orderes id : "1568 -1600"
}
I need to return there name of the customers who order is more than > 1500
You cannot name products orderes id like that.It should not contain any whitespaces in between.If u want to do so, wrap it with "".
Assuming your product ID is unique , u need to treat the value as integer then only my codes work.
Assuming u already solved the problem above, u can simply do
customers = [ { name :" stacy " ,
age : "45",
productsorderedid : 1500
},
{name : "ashley",
age : "87",
productsorderedid : 1660
},
{name: " gabrielle",
age : "67",
productsorderedid : 1600
}]
const filteredcustomers = customers.filter((customer) => customer.productsorderedid > 1500);
console.log(filteredcustomers)

javascript multidimensional objects

I have the following requirements that needs to be build in javascript objects/array. Can anyone help me with a sample?
Requirements
Start with invoices number. Key: invoice, Value: INV001, INV002, INV003...
Each invoice number contain 1 or more receipt number. 1 receipt number may belongs to 1 or more invoices number. Key: receipt, Value: RCP001, RCP002, RCP003...
Each receipt number contain 1 or more payment method. Key: payment, Value: cash, cc, ibg, chq...
Each payment method contain only 1 amount. Key: amount, Value: 5, 10, 1000, 9999...
JavaScript doesn't inherently support multidimensional arrays.
Instead, You need to create an array of arrays. IE
Start with your 3 primary arrays:
var invoiceArr = ["invoice1", "invoice2", "invoice3"];
var receiptArr = ["receipt1", "receipt2", "receipt3"];
var paymentArr = ["payment1", "payment2", "payment3"];
Add them to a main array:
var mainArray = [invoiceArr, receiptArr, paymentArr];
Are you able to follow the below code or do you need further instructions?
var solution = {
invoice: [{"INV1" : { receipt : ["RCP1" : { payment : ["cash" , "cc"]
} , "RCP2"]
}},
{"INV2" : { receipt : ["RCP1", "RCP2"]
}}
],
}

How to find duplicates, count elements in array using javascript/jquery

I have a form in HTML. In this form, I can build catalog preferences.
When I'm done with that I can click on save button and build a next one. The result is saving in an array.
When I have more than one saved catalog(sku=stock keeping unit) in my array it's possible that there are some duplicates. How can I remove the duplicates and count them (The quantity should stay even if there is a duplicate)?
Jsfiddle
Array(Array(
0:5016s18gercol, //sku(stock keeping unit)
1: 100, //quantity
2: 5017ext10002, //extra sku for extra costs(cataloge in color)
3: 1
),
Array(
0:5016s43gerbw, //sku
1: 100, //quantity
2: 5017ext10001,//extra sku for extra costs(catalog own cover)
3: 1 //quanitity extra costs
),
Array(
0: "5016s43gercol" //sku
1: "400" //quantity
2:"5017ext10001" //extra sku (own cover)
3:"1" //quantity sku
4:"5017ext10002" //extra sku (in color)
5:"1" //quantity sku
)
)
This is what i get. It should look like this:
array(5016s18gercol,
500,
5017ext10002,
2,
5017ext10001,
2)
Every sku is unique so i cant have two same sku's. I have to count them if there are more than one.
Use array.prototype.map and array.prototype.some:
var values = [
{ name: 'someName1' },
{ name: 'someName2' },
{ name: 'someName4' },
{ name: 'someName2' }
];
var valueArr = values.map(function(item){ return item.name });
var isDuplicate = valueArr.some(function(item, idx){
return valueArr.indexOf(item) != idx
});
console.log(isDuplicate);

remove and replace item from object in array javascript

I have read and tried all of the posts of SO on this subject, but for some reason none of the answers are providing the desired effect.
I have written a shopping basket program and once the user clicks the'Buy now' button I wish to make POST request containing an object with the users order.
Problem
The user has the option to purchase three different items. Each time the user clicks on an item, which is a html input box, to increase the amount they wish to purchase I want to update the object to only contain the latest amount chosen.
In its simplest format the basket, when initiated, looks like this :
var basket = {items:[
{item:"Trousers", quantity:1, cost:"10"},
{item:"Trainers", quantity:1, cost:"5"},
{item:"Jacket", quantity:1, cost:"30"}
]}
Each time the user clicks the input button I wish for the basket to be updated so if the user clicked to increase the jacket to a quantity of 3, and the trousers to 4 I want the object to look like this:
var basket = {items:[
{item:"Trousers", quantity:4, cost:"40"},
{item:"Trainers", quantity:1, cost:"5"},
{item:"Jacket", quantity:3, cost:"90"}
]}
Then if a user decides to reduce the number of trousers by 1, to 3, I would want the basket.items object to look like this:
var basket = {items:[
{item:"Trousers", quantity:3, cost:"30"},
{item:"Trainers", quantity:1, cost:"5"},
{item:"Jacket", quantity:3, cost:"90"}
]}
I have written the code for all the calculations etc. so this is not the issue but the issue is to update basket.items to only contain the three items listed above at once, with the latest data.
I cannot use the filter method as this needs to work in older versions of IE. I have tried all solutions listed in this and this along with many more but none of these answers are providing the solution I am looking for.
Let me know if any further information is required.
try this:
var basket = {
items: [
{
item: "Trousers",
quantity: 1,
cost: "10"
}, {
item: "Trainers",
quantity: 1,
cost: "5"
}, {
item: "Jacket",
quantity: 1,
cost: "30"
}]
};
function updateBasket(item) {
basket.items = basket.items.map(function (product) {
if (product.item == item.item) return item;
else return product;
});
}
updateBasket({
item: "Jacket",
quantity: 9,
cost: "30"
});
updateBasket({
item: "Trainers",
quantity: 9,
cost: "30"
});
console.log(basket)
Don't know if for you having an array of objects is mandatory if that's not the case you can structure your data differently, for instance
basket = { items : { item_1 : { quantity: 1, cost: 1 } } }
so updating the basket it will be simply
function updateBasket(item, value) {
// item -> item_1
// value - > { quantity: 2, cost: 2}
basket['items'][item] = value;
}
To be honest, I think the problem could be solved if you kept your data in a little different way. For example, something like this
var products = {
trousers:0,
jackets:0,
trainers:0,
};
var prices = {
trainers:5,
jackets: 30,
trousers: 10
}
//to increase the amount of products after user event
products.jackets +=2;
products.trainers +=3;
products.trousers +=1;
//finally generate your desired format
var basket = {items:[]};
for(product in products){
basket.items.push({
item: product,
quantity: products[product],
cost: products[product]*prices[product]
});
}
console.log(basket);
You can see that basket is now in your desired format :)
Cost should be a number and not string.
If you are not keeping a global object for what is the price of 1 item then once you have updated your basket object you will loose the information on price of 1 item and you wouldn't know how much to increase the price.
Considering same, below would be my recommendation of changes:
var basket = {items:[
{item:"Trousers", quantity:4, itemCost:40, totalCost:40},
{item:"Trainers", quantity:1, itemCost:5, totalCost:5},
{item:"Jacket", quantity:3, itemCost:90, totalCost:90},
]}
function updateQuantity(itemName, qIncreaseBy, qDecreaseBy){
console.log(basket);
for(var propt in basket.items){
if(basket.items[propt].item == itemName){
if(qIncreaseBy != 0){
basket.items[propt].quantity = (basket.items[propt].quantity + 1);
basket.items[propt].totalCost = (basket.items[propt].totalCost + basket.items[propt].itemCost);
} else{
basket.items[propt].quantity = (basket.items[propt].quantity - 1);
basket.items[propt].totalCost = (basket.items[propt].totalCost - basket.items[propt].itemCost);
}
break;
}
}
console.log(basket);
}
Usage:
updateQuantity("Trainers", 0, 1); //To add item
updateQuantity("Trainers", 1, 0) //To remove item

Displaying data in Jqgrid

I have a value stored in array variable item like
var item = JSON.stringify(product);
cartproduct[cartproduct.length] = item;
item holds data such as
{
"Product": "1001",
"Brand": "Dell",
"Model": "Inspiron ",
"Price":"25000"
}
Now i want to display this item data in respective jqgrid columns like Product, Brand, Model ..
I saw one jsFiddle example like
http://jsfiddle.net/amorris/yNw3C/
Now all I want is my item value in the format of data.
var data = [[48803, "DSK1", "", "02200220", "OPEN"]];
var item = [[1000,"Sony","Vaio",40000]];
Try this:
var itemFormatted = [[
item.Product,
item.Brand,
item.Model,
item.Price
]];
// Now itemFormatted will be in the correct format
Check out Working with Javascript objects for more information.

Categories

Resources