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.
Related
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',
''
)
);
}
I am working with firebase and javascript. I am trying to return one array from firebase-database after executing a query from two tables. When I console.log my data I get a separate array and object for each bit of data.
var userId = 'hirerId';
var chatIdRef = firebase.database().ref("members");
var chatsRef = firebase.database().ref("chats");
chatIdRef.child(userId).on('child_added', snap => {
chatsRef.child(snap.key).once('value', snap => {
items = [];
items.push({
text: snap.val().text,
chatId: snap.key
});
console.log(items);
});
});
This logs two separate arrays and objects: [{"text":"How are you","chatId":"chatId"}] [{"text":"Hi friend","chatId":"chatId2"}]
My desired result is [{"text": "How are you","chatId":"chatId"}, {"text":"Hi friend","chatId":"chatId2"}]
This is my data structure:
data structure
How can I achieve my desired result? Thanks
just use apply.push to join as many arrays as you want. However, you might want to move your items = []; array outside the function. That's what is causing your problem. You are emptying the array every time you push/function fires.
var ar1 = [{
"text": "How are you",
"chatId": "chatId"
}];
var ar2 = [{
"text": "Hi friend",
"chatId": "chatId2"
}];
ar1.push.apply(ar1, ar2);
console.log(ar1);
i need to create drop
down list based on following json array,there will be 5 drop down list , if i select i need to populate other four for example if i select Hindi in first drop-down list then
Second list Third list Forth list Fifth list
"History", "Philosophy", "Political Science" "English"
"Sociology", "BLANK" "BLANK" "BLANK"
"Economics"
Now when i use jquery to implement this the list is not populating properly.I can not break down the inner array.
i am attaching link of jsfidle.Do i have to change the json format.
{
"Hindi": [
[
"History",
"Sociology",
"Economics"
],
"Philosophy",
"Political Science",
"English"
],
"Bengali": [
["History" ,"Sociology"
],
"Sanskrit",
"Philosophy",
"Political Science"
],
"English": [["History","Sociology","Economics"],
"Philosophy",
"Political Science",
["Bengali","Hindi"]
]
}
When parsing JSON assume that you have the same structure for every dropdown :
{"1select":[["2select values..."],[3select values..."],[4select values..."],[5select values..."]]}
(if there is no array -> create one)
and than do the same for every dropdown.
CODE :
var jsonObj = {"Hindi":[["History","Sociology","Economics"],"Philosophy","Political Science","English"],"Bengali":[["History","Sociology"],"Sanskrit","Philosophy","Political Science"],"English":[["History","Sociology","Economics"],"Philosophy","Political Science",["Bengali","Hindi"]]}
function updateSelect() {
var getOpts = function(raw){
var values = raw;
if (!(raw instanceof Array)){
values = [raw, ""];
}
var result = [];
values.forEach(function(obj){
result.push(new Option(obj, obj));
});
return result;
};
var newKey = $("#select1").val();
var mappings = [{"#select2":0},{"#select3":1},{"#select4":2},{"#select5":3}];
var selected = jsonObj[newKey];
mappings.forEach(function(mapping){
var selector = Object.keys(mapping)[0];
var index = mapping[selector];
$(selector).empty();
var opts = getOpts(selected[index]);
$(selector).append(opts);
});
}
$(document).ready(function() {
$("#select1").change(updateSelect);
updateSelect(); // For initial page load.
});
Example : here
I'm trying to perform what seems like a simple task and display <li>'s for each item in a JSON object. Then, when I click each displayed item, get additional JSON info from all the selected items, and create an array that is stored in a variable for use later.
Here is my JSON. Nothing crazy, simple array of data.
[
{
"subCategory": "Foo",
"total": 100,
"converted": 25,
"revenue": 500
},
{
"subCategory": "Bar",
"total": 100,
"converted": 25,
"revenue": 1000
}
]
With my JS (using jQuery), I'm getting and displaying each item correctly, but I'm not getting the data that I want when i select an item that is getting displayed. In the following JS, I realize I'm not doing much beyond adding the class to the li displayed, but I'm stuck on how to go about getting the data for each selected item and over write the variables below.
(function(){
$('.bubbles').on('click', 'li', function(){
$(this).toggleClass('selected');
});
$.getJSON('data.json', function(data) {
$.each(data,function(i, value){
// Display bubbles
$('.marketingBubbles').append("<li class='"+ value.leads + " "+ value.status + " "+ value.lift + "'>");
// Get data and create arrays
var totalArray = [value.total], // Get values from all totals
convertedArray = [value.converted], // Get all values from converted
revenueArray = [value.revenue]
// Add up numbers in arrays
var totalConverted = eval(convertedArray.join('+')), // Sum of all converted leads
totalLeads = eval(totalArray.join('+')), // Sum of all total leads
totalRevenue = eval(indicatorRevenue.join('+')) // Sum of all revenue
});
});
})();
HTML
<ul class="marketingBubbles"></ul>
Eventually, i would like to take the values within an array, no matter how many times it is changed, perform some simple math operations with the data and display in various divs on the screen.
Any help would be appreciated.
Thank you!
How would you go about getting all inventory locations for a particular item? What I would like is to check if a specific inventory location has any allotted inventory for an item.
I have tried to use the nlapiSearchRecord('item',null,filter,columns) to try this but it only returns the preferred location and not all locations even though their is inventory in the other locations.
Filters were setup as such:
filters = [ new nlobjSearchFilter('internalid',null,'is',10)];
If I add new nlobjSearchFilter('location',null,'is',34) to the filters which is the id for the inventory location I am looking for, I don't get any results at all.
the return I get from the above filters only list the preferred location and not any other locations with available inventory.
-- UPDATE --
After updating the code to use the suggestion below I am now getting the inventory location but not the correct inventory count for the location which should be 5 not 87
var itemId = 3376;
var locationId = 34;
var items = [];
var filters = [];
var columns = [];
filters = [
new nlobjSearchFilter('internalid',null,'is',itemId),
new nlobjSearchFilter('inventorylocation',null,'is',locationId),
new nlobjSearchFilter('quantityavailable',null,'greaterthan',0)
];
columns = [
new nlobjSearchColumn('itemid'),
new nlobjSearchColumn('inventorylocation'),
new nlobjSearchColumn('quantityavailable'),
new nlobjSearchColumn('quantityonhand'),
];
var results = nlapiSearchRecord('item',null,filters,columns);
if (results != null)
{
for (var i=0, l=results.length; i < l; i++)
{
var result = results[i];
items.push(result);
}
}
OUT PUT printed in JSON Format
{
"id": "3376",
"recordtype": "assemblyitem",
"columns": {
"itemid": "Marketing : Misc : T-Shirt Womens Medium",
"inventorylocation": {
"name": "InventoryLocation",
"internalid": "34"
},
"quantityavailable": 87,
"quantityonhand": 90
}
}
Thanks in advance.
I believe the field to use is the 'inventorylocation' field.
You should use the locationquantityavailable and locationquantityonhand columns instead of the ones you are using.
For references to the available columns/fields on a records, you may lookup the "Records Browser" in Help.